VirtualBox

source: vbox/trunk/src/VBox/Frontends/VirtualBox/src/globals/VBoxGlobal.cpp@ 43138

Last change on this file since 43138 was 43127, checked in by vboxsync, 12 years ago

FE/Qt: VBox global stuff: Add additional error-handling to open-session mechanism (for IMachine::LockMachine).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 163.7 KB
Line 
1/* $Id: VBoxGlobal.cpp 43127 2012-08-30 19:26:29Z vboxsync $ */
2/** @file
3 * VBox Qt GUI - VBoxGlobal class implementation.
4 */
5
6/*
7 * Copyright (C) 2006-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/* Qt includes: */
19#include <QProgressDialog>
20#include <QLibraryInfo>
21#include <QFileDialog>
22#include <QToolTip>
23#include <QTranslator>
24#include <QDesktopWidget>
25#include <QDesktopServices>
26#include <QMutex>
27#include <QToolButton>
28#include <QProcess>
29#include <QThread>
30#include <QPainter>
31#include <QSettings>
32#include <QTimer>
33#include <QDir>
34#include <QLocale>
35#include <QNetworkProxy>
36
37#ifdef Q_WS_WIN
38# include <QEventLoop>
39#endif /* Q_WS_WIN */
40
41#ifdef Q_WS_X11
42# include <QTextBrowser>
43# include <QScrollBar>
44# include <QX11Info>
45#endif /* Q_WS_X11 */
46
47#ifdef VBOX_GUI_WITH_PIDFILE
48# include <QTextStream>
49#endif /* VBOX_GUI_WITH_PIDFILE */
50
51/* GUI includes: */
52#include "VBoxGlobal.h"
53#include "VBoxUtils.h"
54#include "UISelectorWindow.h"
55#include "UIMessageCenter.h"
56#include "QIMessageBox.h"
57#include "QIDialogButtonBox.h"
58#include "UIIconPool.h"
59#include "UIActionPoolSelector.h"
60#include "UIActionPoolRuntime.h"
61#include "UIExtraDataEventHandler.h"
62#include "QIFileDialog.h"
63#include "UINetworkManager.h"
64#include "UIUpdateManager.h"
65#include "UIMachine.h"
66#include "UISession.h"
67#include "UIConverter.h"
68
69#ifdef Q_WS_X11
70# include "UIHotKeyEditor.h"
71# ifndef VBOX_OSE
72# include "VBoxLicenseViewer.h"
73# endif /* VBOX_OSE */
74# include "VBoxX11Helper.h"
75#endif /* Q_WS_X11 */
76
77#ifdef Q_WS_MAC
78# include "VBoxUtils-darwin.h"
79# include "UIMachineWindowFullscreen.h"
80# include "UIMachineWindowSeamless.h"
81#endif /* Q_WS_MAC */
82
83#ifdef VBOX_WITH_VIDEOHWACCEL
84# include "VBoxFBOverlay.h"
85#endif /* VBOX_WITH_VIDEOHWACCEL */
86
87#ifdef VBOX_WITH_REGISTRATION
88# include "UIRegistrationWzd.h"
89#endif /* VBOX_WITH_REGISTRATION */
90
91#ifdef VBOX_GUI_WITH_SYSTRAY
92#include <iprt/process.h>
93#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
94#define HOSTSUFF_EXE ".exe"
95#else /* !RT_OS_WINDOWS */
96#define HOSTSUFF_EXE ""
97#endif /* !RT_OS_WINDOWS */
98#endif /* VBOX_GUI_WITH_SYSTRAY */
99
100/* COM includes: */
101#include "CMachine.h"
102#include "CSystemProperties.h"
103#include "CUSBDevice.h"
104#include "CUSBDeviceFilter.h"
105#include "CBIOSSettings.h"
106#include "CVRDEServer.h"
107#include "CStorageController.h"
108#include "CMediumAttachment.h"
109#include "CAudioAdapter.h"
110#include "CNetworkAdapter.h"
111#include "CSerialPort.h"
112#include "CParallelPort.h"
113#include "CUSBController.h"
114#include "CHostUSBDevice.h"
115#include "CMediumFormat.h"
116#include "CSharedFolder.h"
117
118/* Other VBox includes: */
119#include <iprt/asm.h>
120#include <iprt/ctype.h>
121#include <iprt/err.h>
122#include <iprt/param.h>
123#include <iprt/path.h>
124#include <iprt/env.h>
125#include <iprt/file.h>
126#include <iprt/ldr.h>
127#include <iprt/system.h>
128#include <iprt/stream.h>
129
130#include <VBox/vd.h>
131#include <VBox/sup.h>
132#include <VBox/com/Guid.h>
133#include <VBox/VBoxOGLTest.h>
134
135#ifdef Q_WS_X11
136#include <iprt/mem.h>
137#endif /* Q_WS_X11 */
138
139/* External includes: */
140#include <math.h>
141
142#ifdef Q_WS_WIN
143#include "shlobj.h"
144#endif /* Q_WS_WIN */
145
146#ifdef Q_WS_X11
147#undef BOOL /* typedef CARD8 BOOL in Xmd.h conflicts with #define BOOL PRBool
148 * in COMDefs.h. A better fix would be to isolate X11-specific
149 * stuff by placing XX* helpers below to a separate source file. */
150#include <X11/X.h>
151#include <X11/Xmd.h>
152#include <X11/Xlib.h>
153#include <X11/Xatom.h>
154#include <X11/extensions/Xinerama.h>
155#define BOOL PRBool
156#endif /* Q_WS_X11 */
157
158//#define VBOX_WITH_FULL_DETAILS_REPORT /* hidden for now */
159
160//#warning "port me: check this"
161/// @todo bird: Use (U)INT_PTR, (U)LONG_PTR, DWORD_PTR, or (u)intptr_t.
162#if defined(Q_OS_WIN64)
163typedef __int64 Q_LONG; /* word up to 64 bit signed */
164typedef unsigned __int64 Q_ULONG; /* word up to 64 bit unsigned */
165#else
166typedef long Q_LONG; /* word up to 64 bit signed */
167typedef unsigned long Q_ULONG; /* word up to 64 bit unsigned */
168#endif
169
170// VBoxMediaEnumEvent
171/////////////////////////////////////////////////////////////////////////////
172
173class VBoxMediaEnumEvent : public QEvent
174{
175public:
176
177 /** Constructs a regular enum event */
178 VBoxMediaEnumEvent (const UIMedium &aMedium,
179 const VBoxMediaList::iterator &aIterator)
180 : QEvent ((QEvent::Type) MediaEnumEventType)
181 , mMedium (aMedium), mIterator (aIterator), mLast (false)
182 {}
183 /** Constructs the last enum event */
184 VBoxMediaEnumEvent (const VBoxMediaList::iterator &aIterator)
185 : QEvent ((QEvent::Type) MediaEnumEventType)
186 , mIterator (aIterator), mLast (true)
187 {}
188
189 /** Last enumerated medium (not valid when #last is true) */
190 const UIMedium mMedium;
191 /* Iterator which points to the corresponding item in the GUI thread: */
192 const VBoxMediaList::iterator mIterator;
193 /** Whether this is the last event for the given enumeration or not */
194 const bool mLast;
195};
196
197// VBoxGlobal
198////////////////////////////////////////////////////////////////////////////////
199
200static bool sVBoxGlobalInited = false;
201static bool sVBoxGlobalInCleanup = false;
202
203/** @internal
204 *
205 * Special routine to do VBoxGlobal cleanup when the application is being
206 * terminated. It is called before some essential Qt functionality (for
207 * instance, QThread) becomes unavailable, allowing us to use it from
208 * VBoxGlobal::cleanup() if necessary.
209 */
210static void vboxGlobalCleanup()
211{
212 Assert (!sVBoxGlobalInCleanup);
213 sVBoxGlobalInCleanup = true;
214 vboxGlobal().cleanup();
215}
216
217/** @internal
218 *
219 * Determines the rendering mode from the argument. Sets the appropriate
220 * default rendering mode if the argument is NULL.
221 */
222static RenderMode vboxGetRenderMode (const char *aModeStr)
223{
224 RenderMode mode = InvalidRenderMode;
225
226#if defined (Q_WS_MAC) && defined (VBOX_GUI_USE_QUARTZ2D)
227 mode = Quartz2DMode;
228# ifdef RT_ARCH_X86
229 /* Quartz2DMode doesn't refresh correctly on 32-bit Snow Leopard, use image mode. */
230// char szRelease[80];
231// if ( RT_SUCCESS (RTSystemQueryOSInfo (RTSYSOSINFO_RELEASE, szRelease, sizeof (szRelease)))
232// && !strncmp (szRelease, "10.", 3))
233// mode = QImageMode;
234# endif
235#elif (defined (Q_WS_WIN32) || defined (Q_WS_PM) || defined (Q_WS_X11)) && defined (VBOX_GUI_USE_QIMAGE)
236 mode = QImageMode;
237#elif defined (Q_WS_X11) && defined (VBOX_GUI_USE_SDL)
238 mode = SDLMode;
239#elif defined (VBOX_GUI_USE_QIMAGE)
240 mode = QImageMode;
241#else
242# error "Cannot determine the default render mode!"
243#endif
244
245 if (aModeStr)
246 {
247 if (0) ;
248#if defined (VBOX_GUI_USE_QIMAGE)
249 else if (::strcmp (aModeStr, "image") == 0)
250 mode = QImageMode;
251#endif
252#if defined (VBOX_GUI_USE_SDL)
253 else if (::strcmp (aModeStr, "sdl") == 0)
254 mode = SDLMode;
255#endif
256#if defined (VBOX_GUI_USE_DDRAW)
257 else if (::strcmp (aModeStr, "ddraw") == 0)
258 mode = DDRAWMode;
259#endif
260#if defined (VBOX_GUI_USE_QUARTZ2D)
261 else if (::strcmp (aModeStr, "quartz2d") == 0)
262 mode = Quartz2DMode;
263#endif
264#if defined (VBOX_GUI_USE_QGLFB)
265 else if (::strcmp (aModeStr, "qgl") == 0)
266 mode = QGLMode;
267#endif
268//#if defined (VBOX_GUI_USE_QGL)
269// else if (::strcmp (aModeStr, "qgloverlay") == 0)
270// mode = QGLOverlayMode;
271//#endif
272
273 }
274
275 return mode;
276}
277
278/** @class VBoxGlobal
279 *
280 * The VBoxGlobal class encapsulates the global VirtualBox data.
281 *
282 * There is only one instance of this class per VirtualBox application,
283 * the reference to it is returned by the static instance() method, or by
284 * the global vboxGlobal() function, that is just an inlined shortcut.
285 */
286
287VBoxGlobal::VBoxGlobal()
288 : mValid (false)
289 , mSelectorWnd (NULL)
290 , m_pVirtualMachine(0)
291 , mMainWindow (NULL)
292#ifdef VBOX_WITH_REGISTRATION
293 , mRegDlg (NULL)
294#endif
295#ifdef VBOX_GUI_WITH_SYSTRAY
296 , mIsTrayMenu (false)
297 , mIncreasedWindowCounter (false)
298#endif
299 , mMediaEnumThread (NULL)
300 , mIsKWinManaged (false)
301 , mDisablePatm(false)
302 , mDisableCsam(false)
303 , mRecompileSupervisor(false)
304 , mRecompileUser(false)
305 , mWarpPct(100)
306 , mVerString("1.0")
307 , m3DAvailable(false)
308 , mSettingsPwSet(false)
309{
310}
311
312//
313// Public members
314/////////////////////////////////////////////////////////////////////////////
315
316/**
317 * Returns a reference to the global VirtualBox data, managed by this class.
318 *
319 * The main() function of the VBox GUI must call this function soon after
320 * creating a QApplication instance but before opening any of the main windows
321 * (to let the VBoxGlobal initialization procedure use various Qt facilities),
322 * and continue execution only when the isValid() method of the returned
323 * instancereturns true, i.e. do something like:
324 *
325 * @code
326 * if ( !VBoxGlobal::instance().isValid() )
327 * return 1;
328 * @endcode
329 * or
330 * @code
331 * if ( !vboxGlobal().isValid() )
332 * return 1;
333 * @endcode
334 *
335 * @note Some VBoxGlobal methods can be used on a partially constructed
336 * VBoxGlobal instance, i.e. from constructors and methods called
337 * from the VBoxGlobal::init() method, which obtain the instance
338 * using this instance() call or the ::vboxGlobal() function. Currently, such
339 * methods are:
340 * #vmStateText, #vmTypeIcon, #vmTypeText, #vmTypeTextList, #vmTypeFromText.
341 *
342 * @see ::vboxGlobal
343 */
344VBoxGlobal &VBoxGlobal::instance()
345{
346 static VBoxGlobal vboxGlobal_instance;
347
348 if (!sVBoxGlobalInited)
349 {
350 /* check that a QApplication instance is created */
351 if (qApp)
352 {
353 sVBoxGlobalInited = true;
354 vboxGlobal_instance.init();
355 /* add our cleanup handler to the list of Qt post routines */
356 qAddPostRoutine (vboxGlobalCleanup);
357 }
358 else
359 AssertMsgFailed (("Must construct a QApplication first!"));
360 }
361 return vboxGlobal_instance;
362}
363
364VBoxGlobal::~VBoxGlobal()
365{
366 qDeleteAll (mOsTypeIcons);
367}
368
369/* static */
370QString VBoxGlobal::qtRTVersionString()
371{
372 return QString::fromLatin1 (qVersion());
373}
374
375/* static */
376uint VBoxGlobal::qtRTVersion()
377{
378 QString rt_ver_str = VBoxGlobal::qtRTVersionString();
379 return (rt_ver_str.section ('.', 0, 0).toInt() << 16) +
380 (rt_ver_str.section ('.', 1, 1).toInt() << 8) +
381 rt_ver_str.section ('.', 2, 2).toInt();
382}
383
384/* static */
385QString VBoxGlobal::qtCTVersionString()
386{
387 return QString::fromLatin1 (QT_VERSION_STR);
388}
389
390/* static */
391uint VBoxGlobal::qtCTVersion()
392{
393 QString ct_ver_str = VBoxGlobal::qtCTVersionString();
394 return (ct_ver_str.section ('.', 0, 0).toInt() << 16) +
395 (ct_ver_str.section ('.', 1, 1).toInt() << 8) +
396 ct_ver_str.section ('.', 2, 2).toInt();
397}
398
399QString VBoxGlobal::vboxVersionString() const
400{
401 return mVBox.GetVersion();
402}
403
404QString VBoxGlobal::vboxVersionStringNormalized() const
405{
406 return mVBox.GetVersionNormalized();
407}
408
409bool VBoxGlobal::isBeta() const
410{
411 return mVBox.GetVersion().contains("BETA", Qt::CaseInsensitive);
412}
413
414/**
415 * Sets the new global settings and saves them to the VirtualBox server.
416 */
417bool VBoxGlobal::setSettings (VBoxGlobalSettings &gs)
418{
419 gs.save (mVBox);
420
421 if (!mVBox.isOk())
422 {
423 msgCenter().cannotSaveGlobalConfig (mVBox);
424 return false;
425 }
426
427 /* We don't assign gs to our gset member here, because VBoxCallback
428 * will update gset as necessary when new settings are successfully
429 * sent to the VirtualBox server by gs.save(). */
430
431 return true;
432}
433
434/**
435 * Returns a reference to the main VBox VM Selector window.
436 * The reference is valid until application termination.
437 *
438 * There is only one such a window per VirtualBox application.
439 */
440UISelectorWindow &VBoxGlobal::selectorWnd()
441{
442 AssertMsg (!vboxGlobal().isVMConsoleProcess(),
443 ("Must NOT be a VM console process"));
444 Assert (mValid);
445
446 if (!mSelectorWnd)
447 {
448 /*
449 * We pass the address of mSelectorWnd to the constructor to let it be
450 * initialized right after the constructor is called. It is necessary
451 * to avoid recursion, since this method may be (and will be) called
452 * from the below constructor or from constructors/methods it calls.
453 */
454 UISelectorWindow *w = new UISelectorWindow (&mSelectorWnd, 0);
455 Assert (w == mSelectorWnd);
456 NOREF(w);
457 }
458
459 return *mSelectorWnd;
460}
461
462bool VBoxGlobal::startMachine(const QString &strMachineId)
463{
464 /* Some restrictions: */
465 AssertMsg(mValid, ("VBoxGlobal is invalid"));
466 AssertMsg(!m_pVirtualMachine, ("Machine already started"));
467
468 /* Create VM session: */
469 CSession session = vboxGlobal().openSession(strMachineId, KLockType_VM);
470 if (session.isNull())
471 return false;
472
473 /* Start virtual machine: */
474 UIMachine *pVirtualMachine = new UIMachine(&m_pVirtualMachine, session);
475 Assert(pVirtualMachine == m_pVirtualMachine);
476 Q_UNUSED(pVirtualMachine);
477 return true;
478}
479
480UIMachine* VBoxGlobal::virtualMachine()
481{
482 return m_pVirtualMachine;
483}
484
485QWidget* VBoxGlobal::vmWindow()
486{
487 if (isVMConsoleProcess() && m_pVirtualMachine)
488 return m_pVirtualMachine->mainWindow();
489 return 0;
490}
491
492#ifdef VBOX_GUI_WITH_PIDFILE
493void VBoxGlobal::createPidfile()
494{
495 if (!m_strPidfile.isEmpty())
496 {
497 qint64 pid = qApp->applicationPid();
498 QFile file(m_strPidfile);
499 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate))
500 {
501 QTextStream out(&file);
502 out << pid << endl;
503 }
504 else
505 LogRel(("Failed to create pid file %s\n", m_strPidfile.toUtf8().constData()));
506 }
507}
508
509void VBoxGlobal::deletePidfile()
510{
511 if ( !m_strPidfile.isEmpty()
512 && QFile::exists(m_strPidfile))
513 QFile::remove(m_strPidfile);
514}
515#endif
516
517bool VBoxGlobal::brandingIsActive (bool aForce /* = false*/)
518{
519 if (aForce)
520 return true;
521
522 if (mBrandingConfig.isEmpty())
523 {
524 mBrandingConfig = QDir(QApplication::applicationDirPath()).absolutePath();
525 mBrandingConfig += "/custom/custom.ini";
526 }
527 return QFile::exists (mBrandingConfig);
528}
529
530/**
531 * Gets a value from the custom .ini file
532 */
533QString VBoxGlobal::brandingGetKey (QString aKey)
534{
535 QSettings s(mBrandingConfig, QSettings::IniFormat);
536 return s.value(QString("%1").arg(aKey)).toString();
537}
538
539#ifdef VBOX_GUI_WITH_SYSTRAY
540
541/**
542 * Returns true if the current instance a systray menu only (started with
543 * "-systray" parameter).
544 */
545bool VBoxGlobal::isTrayMenu() const
546{
547 return mIsTrayMenu;
548}
549
550void VBoxGlobal::setTrayMenu(bool aIsTrayMenu)
551{
552 mIsTrayMenu = aIsTrayMenu;
553}
554
555/**
556 * Spawns a new selector window (process).
557 */
558void VBoxGlobal::trayIconShowSelector()
559{
560 /* Get the path to the executable. */
561 char path[RTPATH_MAX];
562 RTPathAppPrivateArch(path, RTPATH_MAX);
563 size_t sz = strlen(path);
564 path[sz++] = RTPATH_DELIMITER;
565 path[sz] = 0;
566 char *cmd = path + sz;
567 sz = RTPATH_MAX - sz;
568
569 int rc = 0;
570 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
571 Assert(sz >= sizeof(VirtualBox_exe));
572 strcpy(cmd, VirtualBox_exe);
573 const char * args[] = {path, 0 };
574 rc = RTProcCreate(path, args, RTENV_DEFAULT, RTPROC_FLAGS_DETACHED, NULL);
575 if (RT_FAILURE(rc))
576 LogRel(("Systray: Failed to start new selector window! Path=%s, rc=%Rrc\n", path, rc));
577}
578
579/**
580 * Tries to install the tray icon using the current instance (singleton).
581 * Returns true if this instance is the tray icon, false if not.
582 */
583bool VBoxGlobal::trayIconInstall()
584{
585 int rc = 0;
586 QString strTrayWinID = mVBox.GetExtraData(GUI_TrayIconWinID);
587 if (false == strTrayWinID.isEmpty())
588 {
589 /* Check if current tray icon is alive by writing some bogus value. */
590 mVBox.SetExtraData(GUI_TrayIconWinID, "0");
591 if (mVBox.isOk())
592 {
593 /* Current tray icon died - clean up. */
594 mVBox.SetExtraData(GUI_TrayIconWinID, NULL);
595 strTrayWinID.clear();
596 }
597 }
598
599 /* Is there already a tray icon or is tray icon not active? */
600 if ( (mIsTrayMenu == false)
601 && (vboxGlobal().settings().trayIconEnabled())
602 && (QSystemTrayIcon::isSystemTrayAvailable())
603 && (strTrayWinID.isEmpty()))
604 {
605 /* Get the path to the executable. */
606 char path[RTPATH_MAX];
607 RTPathAppPrivateArch(path, RTPATH_MAX);
608 size_t sz = strlen(path);
609 path[sz++] = RTPATH_DELIMITER;
610 path[sz] = 0;
611 char *cmd = path + sz;
612 sz = RTPATH_MAX - sz;
613
614 const char VirtualBox_exe[] = "VirtualBox" HOSTSUFF_EXE;
615 Assert(sz >= sizeof(VirtualBox_exe));
616 strcpy(cmd, VirtualBox_exe);
617 const char * args[] = {path, "-systray", 0 };
618 rc = RTProcCreate(path, args, RTENV_DEFAULT, RTPROC_FLAGS_DETACHED, NULL);
619 if (RT_FAILURE(rc))
620 {
621 LogRel(("Systray: Failed to start systray window! Path=%s, rc=%Rrc\n", path, rc));
622 return false;
623 }
624 }
625
626 if (mIsTrayMenu)
627 {
628 // Use this selector for displaying the tray icon
629 mVBox.SetExtraData(GUI_TrayIconWinID,
630 QString("%1").arg((qulonglong)vboxGlobal().mainWindow()->winId()));
631
632 /* The first process which can grab this "mutex" will win ->
633 * It will be the tray icon menu then. */
634 if (mVBox.isOk())
635 {
636 emit sigTrayIconShow(true);
637 return true;
638 }
639 }
640
641 return false;
642}
643
644#endif
645
646#ifdef Q_WS_X11
647QList<QRect> XGetDesktopList()
648{
649 /* Prepare empty resulting list: */
650 QList<QRect> result;
651
652 /* Get current display: */
653 Display* pDisplay = QX11Info::display();
654
655 /* If it's a Xinerama desktop: */
656 if (XineramaIsActive(pDisplay))
657 {
658 /* Reading Xinerama data: */
659 int iScreens = 0;
660 XineramaScreenInfo *pScreensData = XineramaQueryScreens(pDisplay, &iScreens);
661
662 /* Fill resulting list: */
663 for (int i = 0; i < iScreens; ++ i)
664 result << QRect(pScreensData[i].x_org, pScreensData[i].y_org,
665 pScreensData[i].width, pScreensData[i].height);
666
667 /* Free screens data: */
668 XFree(pScreensData);
669 }
670
671 /* Return resulting list: */
672 return result;
673}
674
675QList<Window> XGetWindowIDList()
676{
677 /* Get current display: */
678 Display *pDisplay = QX11Info::display();
679
680 /* Get virtual desktop window: */
681 Window window = QX11Info::appRootWindow();
682
683 /* Get 'client list' atom: */
684 Atom propNameAtom = XInternAtom(pDisplay, "_NET_CLIENT_LIST", True /* only if exists */);
685
686 /* Prepare empty resulting list: */
687 QList<Window> result;
688
689 /* If atom does not exists return empty list: */
690 if (propNameAtom == None)
691 return result;
692
693 /* Get atom value: */
694 Atom realAtomType = None;
695 int iRealFormat = 0;
696 unsigned long uItemsCount = 0;
697 unsigned long uBytesAfter = 0;
698 unsigned char *pData = 0;
699 int rc = XGetWindowProperty(pDisplay, window, propNameAtom,
700 0, 0x7fffffff /*LONG_MAX*/, False /* delete */,
701 XA_WINDOW, &realAtomType, &iRealFormat,
702 &uItemsCount, &uBytesAfter, &pData);
703
704 /* If get property is failed return empty list: */
705 if (rc != Success)
706 return result;
707
708 /* Fill resulting list with win ids: */
709 Window *pWindowData = reinterpret_cast<Window*>(pData);
710 for (ulong i = 0; i < uItemsCount; ++ i)
711 result << pWindowData[i];
712
713 /* Releasing resources: */
714 XFree(pData);
715
716 /* Return resulting list: */
717 return result;
718}
719
720QList<ulong> XGetStrut(Window window)
721{
722 /* Get current display: */
723 Display *pDisplay = QX11Info::display();
724
725 /* Get 'strut' atom: */
726 Atom propNameAtom = XInternAtom(pDisplay, "_NET_WM_STRUT_PARTIAL", True /* only if exists */);
727
728 /* Prepare empty resulting list: */
729 QList<ulong> result;
730
731 /* If atom does not exists return empty list: */
732 if (propNameAtom == None)
733 return result;
734
735 /* Get atom value: */
736 Atom realAtomType = None;
737 int iRealFormat = 0;
738 ulong uItemsCount = 0;
739 ulong uBytesAfter = 0;
740 unsigned char *pData = 0;
741 int rc = XGetWindowProperty(pDisplay, window, propNameAtom,
742 0, LONG_MAX, False /* delete */,
743 XA_CARDINAL, &realAtomType, &iRealFormat,
744 &uItemsCount, &uBytesAfter, &pData);
745
746 /* If get property is failed return empty list: */
747 if (rc != Success)
748 return result;
749
750 /* Fill resulting list with strut shifts: */
751 ulong *pStrutsData = reinterpret_cast<ulong*>(pData);
752 for (ulong i = 0; i < uItemsCount; ++ i)
753 result << pStrutsData[i];
754
755 /* Releasing resources: */
756 XFree(pData);
757
758 /* Return resulting list: */
759 return result;
760}
761#endif /* ifdef Q_WS_X11 */
762
763const QRect VBoxGlobal::availableGeometry(int iScreen) const
764{
765 /* Prepare empty result: */
766 QRect result;
767
768#ifdef Q_WS_X11
769
770 /* Get current display: */
771 Display* pDisplay = QX11Info::display();
772
773 /* Get current application desktop: */
774 QDesktopWidget *pDesktopWidget = QApplication::desktop();
775
776 /* If it's a virtual desktop: */
777 if (pDesktopWidget->isVirtualDesktop())
778 {
779 /* If it's a Xinerama desktop: */
780 if (XineramaIsActive(pDisplay))
781 {
782 /* Get desktops list: */
783 QList<QRect> desktops = XGetDesktopList();
784
785 /* Combine to get full virtual region: */
786 QRegion virtualRegion;
787 foreach (QRect desktop, desktops)
788 virtualRegion += desktop;
789 virtualRegion = virtualRegion.boundingRect();
790
791 /* Remember initial virtual desktop: */
792 QRect virtualDesktop = virtualRegion.boundingRect();
793 //AssertMsgFailed(("LOG... Virtual desktop is: %dx%dx%dx%d\n", virtualDesktop.x(), virtualDesktop.y(),
794 // virtualDesktop.width(), virtualDesktop.height()));
795
796 /* Set available geometry to screen geometry initially: */
797 result = desktops[iScreen];
798
799 /* Feat available geometry of virtual desktop to respect all the struts: */
800 QList<Window> list = XGetWindowIDList();
801 for (int i = 0; i < list.size(); ++ i)
802 {
803 /* Get window: */
804 Window wid = list[i];
805 QList<ulong> struts = XGetStrut(wid);
806
807 /* If window has strut: */
808 if (struts.size())
809 {
810 ulong uLeftShift = struts[0];
811 ulong uLeftFromY = struts[4];
812 ulong uLeftToY = struts[5];
813
814 ulong uRightShift = struts[1];
815 ulong uRightFromY = struts[6];
816 ulong uRightToY = struts[7];
817
818 ulong uTopShift = struts[2];
819 ulong uTopFromX = struts[8];
820 ulong uTopToX = struts[9];
821
822 ulong uBottomShift = struts[3];
823 ulong uBottomFromX = struts[10];
824 ulong uBottomToX = struts[11];
825
826 if (uLeftShift)
827 {
828 QRect sr(QPoint(0, uLeftFromY),
829 QSize(uLeftShift, uLeftToY - uLeftFromY + 1));
830
831 //AssertMsgFailed(("LOG... Subtract left strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
832 virtualRegion -= sr;
833 }
834
835 if (uRightShift)
836 {
837 QRect sr(QPoint(virtualDesktop.x() + virtualDesktop.width() - uRightShift, uRightFromY),
838 QSize(virtualDesktop.x() + virtualDesktop.width(), uRightToY - uRightFromY + 1));
839
840 //AssertMsgFailed(("LOG... Subtract right strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
841 virtualRegion -= sr;
842 }
843
844 if (uTopShift)
845 {
846 QRect sr(QPoint(uTopFromX, 0),
847 QSize(uTopToX - uTopFromX + 1, uTopShift));
848
849 //AssertMsgFailed(("LOG... Subtract top strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
850 virtualRegion -= sr;
851 }
852
853 if (uBottomShift)
854 {
855 QRect sr(QPoint(uBottomFromX, virtualDesktop.y() + virtualDesktop.height() - uBottomShift),
856 QSize(uBottomToX - uBottomFromX + 1, uBottomShift));
857
858 //AssertMsgFailed(("LOG... Subtract bottom strut: top-left: %dx%d, size: %dx%d\n", sr.x(), sr.y(), sr.width(), sr.height()));
859 virtualRegion -= sr;
860 }
861 }
862 }
863
864 /* Get final available geometry: */
865 result = (virtualRegion & result).boundingRect();
866 }
867 }
868
869 /* If result is still NULL: */
870 if (result.isNull())
871 {
872 /* Use QT default functionality: */
873 result = pDesktopWidget->availableGeometry(iScreen);
874 }
875
876 //AssertMsgFailed(("LOG... Final geometry: %dx%dx%dx%d\n", result.x(), result.y(), result.width(), result.height()));
877
878#else /* ifdef Q_WS_X11 */
879
880 result = QApplication::desktop()->availableGeometry(iScreen);
881
882#endif /* ifndef Q_WS_X11 */
883
884 return result;
885}
886
887/**
888 * Returns the list of few guest OS types, queried from
889 * IVirtualBox corresponding to every family id.
890 */
891QList <CGuestOSType> VBoxGlobal::vmGuestOSFamilyList() const
892{
893 QList <CGuestOSType> result;
894 for (int i = 0 ; i < mFamilyIDs.size(); ++ i)
895 result << mTypes [i][0];
896 return result;
897}
898
899/**
900 * Returns the list of all guest OS types, queried from
901 * IVirtualBox corresponding to passed family id.
902 */
903QList <CGuestOSType> VBoxGlobal::vmGuestOSTypeList (const QString &aFamilyId) const
904{
905 AssertMsg (mFamilyIDs.contains (aFamilyId), ("Family ID incorrect: '%s'.", aFamilyId.toLatin1().constData()));
906 return mFamilyIDs.contains (aFamilyId) ?
907 mTypes [mFamilyIDs.indexOf (aFamilyId)] : QList <CGuestOSType>();
908}
909
910/**
911 * Returns the icon corresponding to the given guest OS type id.
912 */
913QPixmap VBoxGlobal::vmGuestOSTypeIcon (const QString &aTypeId) const
914{
915 static const QPixmap none;
916 QPixmap *p = mOsTypeIcons.value (aTypeId);
917 AssertMsg (p, ("Icon for type '%s' must be defined.", aTypeId.toLatin1().constData()));
918 return p ? *p : none;
919}
920
921/**
922 * Returns the guest OS type object corresponding to the given type id of list
923 * containing OS types related to OS family determined by family id attribute.
924 * If the index is invalid a null object is returned.
925 */
926CGuestOSType VBoxGlobal::vmGuestOSType (const QString &aTypeId,
927 const QString &aFamilyId /* = QString::null */) const
928{
929 QList <CGuestOSType> list;
930 if (mFamilyIDs.contains (aFamilyId))
931 {
932 list = mTypes [mFamilyIDs.indexOf (aFamilyId)];
933 }
934 else
935 {
936 for (int i = 0; i < mFamilyIDs.size(); ++ i)
937 list += mTypes [i];
938 }
939 for (int j = 0; j < list.size(); ++ j)
940 if (!list [j].GetId().compare (aTypeId))
941 return list [j];
942 AssertMsgFailed (("Type ID incorrect: '%s'.", aTypeId.toLatin1().constData()));
943 return CGuestOSType();
944}
945
946/**
947 * Returns the description corresponding to the given guest OS type id.
948 */
949QString VBoxGlobal::vmGuestOSTypeDescription (const QString &aTypeId) const
950{
951 for (int i = 0; i < mFamilyIDs.size(); ++ i)
952 {
953 QList <CGuestOSType> list (mTypes [i]);
954 for ( int j = 0; j < list.size(); ++ j)
955 if (!list [j].GetId().compare (aTypeId))
956 return list [j].GetDescription();
957 }
958 return QString::null;
959}
960
961struct PortConfig
962{
963 const char *name;
964 const ulong IRQ;
965 const ulong IOBase;
966};
967
968static const PortConfig kComKnownPorts[] =
969{
970 { "COM1", 4, 0x3F8 },
971 { "COM2", 3, 0x2F8 },
972 { "COM3", 4, 0x3E8 },
973 { "COM4", 3, 0x2E8 },
974 /* must not contain an element with IRQ=0 and IOBase=0 used to cause
975 * toCOMPortName() to return the "User-defined" string for these values. */
976};
977
978static const PortConfig kLptKnownPorts[] =
979{
980 { "LPT1", 7, 0x378 },
981 { "LPT2", 5, 0x278 },
982 { "LPT1", 2, 0x3BC },
983 /* must not contain an element with IRQ=0 and IOBase=0 used to cause
984 * toLPTPortName() to return the "User-defined" string for these values. */
985};
986
987/**
988 * Similar to toString (KMediumType), but returns 'Differencing' for
989 * normal hard disks that have a parent.
990 */
991QString VBoxGlobal::mediumTypeString(const CMedium &medium) const
992{
993 if (!medium.GetParent().isNull())
994 {
995 Assert(medium.GetType() == KMediumType_Normal);
996 return mDiskTypes_Differencing;
997 }
998 return gpConverter->toString(medium.GetType());
999}
1000
1001/**
1002 * Returns the list of the standard COM port names (i.e. "COMx").
1003 */
1004QStringList VBoxGlobal::COMPortNames() const
1005{
1006 QStringList list;
1007 for (size_t i = 0; i < RT_ELEMENTS (kComKnownPorts); ++ i)
1008 list << kComKnownPorts [i].name;
1009
1010 return list;
1011}
1012
1013/**
1014 * Returns the list of the standard LPT port names (i.e. "LPTx").
1015 */
1016QStringList VBoxGlobal::LPTPortNames() const
1017{
1018 QStringList list;
1019 for (size_t i = 0; i < RT_ELEMENTS (kLptKnownPorts); ++ i)
1020 list << kLptKnownPorts [i].name;
1021
1022 return list;
1023}
1024
1025/**
1026 * Returns the name of the standard COM port corresponding to the given
1027 * parameters, or "User-defined" (which is also returned when both
1028 * @a aIRQ and @a aIOBase are 0).
1029 */
1030QString VBoxGlobal::toCOMPortName (ulong aIRQ, ulong aIOBase) const
1031{
1032 for (size_t i = 0; i < RT_ELEMENTS (kComKnownPorts); ++ i)
1033 if (kComKnownPorts [i].IRQ == aIRQ &&
1034 kComKnownPorts [i].IOBase == aIOBase)
1035 return kComKnownPorts [i].name;
1036
1037 return mUserDefinedPortName;
1038}
1039
1040/**
1041 * Returns the name of the standard LPT port corresponding to the given
1042 * parameters, or "User-defined" (which is also returned when both
1043 * @a aIRQ and @a aIOBase are 0).
1044 */
1045QString VBoxGlobal::toLPTPortName (ulong aIRQ, ulong aIOBase) const
1046{
1047 for (size_t i = 0; i < RT_ELEMENTS (kLptKnownPorts); ++ i)
1048 if (kLptKnownPorts [i].IRQ == aIRQ &&
1049 kLptKnownPorts [i].IOBase == aIOBase)
1050 return kLptKnownPorts [i].name;
1051
1052 return mUserDefinedPortName;
1053}
1054
1055/**
1056 * Returns port parameters corresponding to the given standard COM name.
1057 * Returns @c true on success, or @c false if the given port name is not one
1058 * of the standard names (i.e. "COMx").
1059 */
1060bool VBoxGlobal::toCOMPortNumbers (const QString &aName, ulong &aIRQ,
1061 ulong &aIOBase) const
1062{
1063 for (size_t i = 0; i < RT_ELEMENTS (kComKnownPorts); ++ i)
1064 if (strcmp (kComKnownPorts [i].name, aName.toUtf8().data()) == 0)
1065 {
1066 aIRQ = kComKnownPorts [i].IRQ;
1067 aIOBase = kComKnownPorts [i].IOBase;
1068 return true;
1069 }
1070
1071 return false;
1072}
1073
1074/**
1075 * Returns port parameters corresponding to the given standard LPT name.
1076 * Returns @c true on success, or @c false if the given port name is not one
1077 * of the standard names (i.e. "LPTx").
1078 */
1079bool VBoxGlobal::toLPTPortNumbers (const QString &aName, ulong &aIRQ,
1080 ulong &aIOBase) const
1081{
1082 for (size_t i = 0; i < RT_ELEMENTS (kLptKnownPorts); ++ i)
1083 if (strcmp (kLptKnownPorts [i].name, aName.toUtf8().data()) == 0)
1084 {
1085 aIRQ = kLptKnownPorts [i].IRQ;
1086 aIOBase = kLptKnownPorts [i].IOBase;
1087 return true;
1088 }
1089
1090 return false;
1091}
1092
1093/**
1094 * Searches for the given hard disk in the list of known media descriptors and
1095 * calls UIMedium::details() on the found descriptor.
1096 *
1097 * If the requested hard disk is not found (for example, it's a new hard disk
1098 * for a new VM created outside our UI), then media enumeration is requested and
1099 * the search is repeated. We assume that the second attempt always succeeds and
1100 * assert otherwise.
1101 *
1102 * @note Technically, the second attempt may fail if, for example, the new hard
1103 * passed to this method disk gets removed before #startEnumeratingMedia()
1104 * succeeds. This (unexpected object uninitialization) is a generic
1105 * problem though and needs to be addressed using exceptions (see also the
1106 * @todo in UIMedium::details()).
1107 */
1108QString VBoxGlobal::details (const CMedium &aMedium, bool aPredictDiff, bool fUseHtml /* = true */)
1109{
1110 CMedium cmedium (aMedium);
1111 UIMedium medium;
1112
1113 if (!findMedium (cmedium, medium))
1114 {
1115 /* Medium may be new and not already in the media list, request refresh */
1116 startEnumeratingMedia();
1117 if (!findMedium (cmedium, medium))
1118 /* Medium might be deleted already, return null string */
1119 return QString();
1120 }
1121
1122 return fUseHtml ? medium.detailsHTML (true /* aNoDiffs */, aPredictDiff) :
1123 medium.details(true /* aNoDiffs */, aPredictDiff);
1124}
1125
1126/**
1127 * Returns the details of the given USB device as a single-line string.
1128 */
1129QString VBoxGlobal::details (const CUSBDevice &aDevice) const
1130{
1131 QString sDetails;
1132 if (aDevice.isNull())
1133 sDetails = tr("Unknown device", "USB device details");
1134 else
1135 {
1136 QString m = aDevice.GetManufacturer().trimmed();
1137 QString p = aDevice.GetProduct().trimmed();
1138
1139 if (m.isEmpty() && p.isEmpty())
1140 {
1141 sDetails =
1142 tr ("Unknown device %1:%2", "USB device details")
1143 .arg (QString().sprintf ("%04hX", aDevice.GetVendorId()))
1144 .arg (QString().sprintf ("%04hX", aDevice.GetProductId()));
1145 }
1146 else
1147 {
1148 if (p.toUpper().startsWith (m.toUpper()))
1149 sDetails = p;
1150 else
1151 sDetails = m + " " + p;
1152 }
1153 ushort r = aDevice.GetRevision();
1154 if (r != 0)
1155 sDetails += QString().sprintf (" [%04hX]", r);
1156 }
1157
1158 return sDetails.trimmed();
1159}
1160
1161/**
1162 * Returns the multi-line description of the given USB device.
1163 */
1164QString VBoxGlobal::toolTip (const CUSBDevice &aDevice) const
1165{
1166 QString tip =
1167 tr ("<nobr>Vendor ID: %1</nobr><br>"
1168 "<nobr>Product ID: %2</nobr><br>"
1169 "<nobr>Revision: %3</nobr>", "USB device tooltip")
1170 .arg (QString().sprintf ("%04hX", aDevice.GetVendorId()))
1171 .arg (QString().sprintf ("%04hX", aDevice.GetProductId()))
1172 .arg (QString().sprintf ("%04hX", aDevice.GetRevision()));
1173
1174 QString ser = aDevice.GetSerialNumber();
1175 if (!ser.isEmpty())
1176 tip += QString (tr ("<br><nobr>Serial No. %1</nobr>", "USB device tooltip"))
1177 .arg (ser);
1178
1179 /* add the state field if it's a host USB device */
1180 CHostUSBDevice hostDev (aDevice);
1181 if (!hostDev.isNull())
1182 {
1183 tip += QString (tr ("<br><nobr>State: %1</nobr>", "USB device tooltip"))
1184 .arg (gpConverter->toString (hostDev.GetState()));
1185 }
1186
1187 return tip;
1188}
1189
1190/**
1191 * Returns the multi-line description of the given USB filter
1192 */
1193QString VBoxGlobal::toolTip (const CUSBDeviceFilter &aFilter) const
1194{
1195 QString tip;
1196
1197 QString vendorId = aFilter.GetVendorId();
1198 if (!vendorId.isEmpty())
1199 tip += tr ("<nobr>Vendor ID: %1</nobr>", "USB filter tooltip")
1200 .arg (vendorId);
1201
1202 QString productId = aFilter.GetProductId();
1203 if (!productId.isEmpty())
1204 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Product ID: %2</nobr>", "USB filter tooltip")
1205 .arg (productId);
1206
1207 QString revision = aFilter.GetRevision();
1208 if (!revision.isEmpty())
1209 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Revision: %3</nobr>", "USB filter tooltip")
1210 .arg (revision);
1211
1212 QString product = aFilter.GetProduct();
1213 if (!product.isEmpty())
1214 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Product: %4</nobr>", "USB filter tooltip")
1215 .arg (product);
1216
1217 QString manufacturer = aFilter.GetManufacturer();
1218 if (!manufacturer.isEmpty())
1219 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Manufacturer: %5</nobr>", "USB filter tooltip")
1220 .arg (manufacturer);
1221
1222 QString serial = aFilter.GetSerialNumber();
1223 if (!serial.isEmpty())
1224 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Serial No.: %1</nobr>", "USB filter tooltip")
1225 .arg (serial);
1226
1227 QString port = aFilter.GetPort();
1228 if (!port.isEmpty())
1229 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Port: %1</nobr>", "USB filter tooltip")
1230 .arg (port);
1231
1232 /* add the state field if it's a host USB device */
1233 CHostUSBDevice hostDev (aFilter);
1234 if (!hostDev.isNull())
1235 {
1236 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>State: %1</nobr>", "USB filter tooltip")
1237 .arg (gpConverter->toString (hostDev.GetState()));
1238 }
1239
1240 return tip;
1241}
1242
1243/**
1244 * Returns a details report on a given VM represented as a HTML table.
1245 *
1246 * @param aMachine Machine to create a report for.
1247 * @param aWithLinks @c true if section titles should be hypertext links.
1248 */
1249QString VBoxGlobal::detailsReport (const CMachine &aMachine, bool aWithLinks)
1250{
1251 /* Details templates */
1252 static const char *sTableTpl =
1253 "<table border=0 cellspacing=1 cellpadding=0>%1</table>";
1254 static const char *sSectionHrefTpl =
1255 "<tr><td width=22 rowspan=%1 align=left><img src='%2'></td>"
1256 "<td colspan=3><b><a href='%3'><nobr>%4</nobr></a></b></td></tr>"
1257 "%5"
1258 "<tr><td colspan=3><font size=1>&nbsp;</font></td></tr>";
1259 static const char *sSectionBoldTpl =
1260 "<tr><td width=22 rowspan=%1 align=left><img src='%2'></td>"
1261 "<td colspan=3><!-- %3 --><b><nobr>%4</nobr></b></td></tr>"
1262 "%5"
1263 "<tr><td colspan=3><font size=1>&nbsp;</font></td></tr>";
1264 static const char *sSectionItemTpl1 =
1265 "<tr><td width=40%><nobr><i>%1</i></nobr></td><td/><td/></tr>";
1266 static const char *sSectionItemTpl2 =
1267 "<tr><td width=40%><nobr>%1:</nobr></td><td/><td>%2</td></tr>";
1268 static const char *sSectionItemTpl3 =
1269 "<tr><td width=40%><nobr>%1</nobr></td><td/><td/></tr>";
1270
1271 const QString &sectionTpl = aWithLinks ? sSectionHrefTpl : sSectionBoldTpl;
1272
1273 /* Compose details report */
1274 QString report;
1275
1276 /* General */
1277 {
1278 QString item = QString (sSectionItemTpl2).arg (tr ("Name", "details report"),
1279 aMachine.GetName())
1280 + QString (sSectionItemTpl2).arg (tr ("OS Type", "details report"),
1281 vmGuestOSTypeDescription (aMachine.GetOSTypeId()));
1282
1283 report += sectionTpl
1284 .arg (2 + 2) /* rows */
1285 .arg (":/machine_16px.png", /* icon */
1286 "#general", /* link */
1287 tr ("General", "details report"), /* title */
1288 item); /* items */
1289 }
1290
1291 /* System */
1292 {
1293 /* BIOS Settings holder */
1294 CBIOSSettings biosSettings = aMachine.GetBIOSSettings();
1295
1296 /* System details row count: */
1297 int iRowCount = 2; /* Memory & CPU details rows initially. */
1298
1299 /* Boot order */
1300 QString bootOrder;
1301 for (ulong i = 1; i <= mVBox.GetSystemProperties().GetMaxBootPosition(); ++ i)
1302 {
1303 KDeviceType device = aMachine.GetBootOrder (i);
1304 if (device == KDeviceType_Null)
1305 continue;
1306 if (!bootOrder.isEmpty())
1307 bootOrder += ", ";
1308 bootOrder += gpConverter->toString (device);
1309 }
1310 if (bootOrder.isEmpty())
1311 bootOrder = gpConverter->toString (KDeviceType_Null);
1312
1313 iRowCount += 1; /* Boot-order row. */
1314
1315#ifdef VBOX_WITH_FULL_DETAILS_REPORT
1316 /* ACPI */
1317 QString acpi = biosSettings.GetACPIEnabled()
1318 ? tr ("Enabled", "details report (ACPI)")
1319 : tr ("Disabled", "details report (ACPI)");
1320
1321 /* IO APIC */
1322 QString ioapic = biosSettings.GetIOAPICEnabled()
1323 ? tr ("Enabled", "details report (IO APIC)")
1324 : tr ("Disabled", "details report (IO APIC)");
1325
1326 /* PAE/NX */
1327 QString pae = aMachine.GetCpuProperty(KCpuPropertyType_PAE)
1328 ? tr ("Enabled", "details report (PAE/NX)")
1329 : tr ("Disabled", "details report (PAE/NX)");
1330
1331 iRowCount += 3; /* Full report rows. */
1332#endif /* VBOX_WITH_FULL_DETAILS_REPORT */
1333
1334 /* VT-x/AMD-V */
1335 QString virt = aMachine.GetHWVirtExProperty(KHWVirtExPropertyType_Enabled)
1336 ? tr ("Enabled", "details report (VT-x/AMD-V)")
1337 : tr ("Disabled", "details report (VT-x/AMD-V)");
1338
1339 /* Nested Paging */
1340 QString nested = aMachine.GetHWVirtExProperty(KHWVirtExPropertyType_NestedPaging)
1341 ? tr ("Enabled", "details report (Nested Paging)")
1342 : tr ("Disabled", "details report (Nested Paging)");
1343
1344 /* VT-x/AMD-V availability: */
1345 bool fVTxAMDVSupported = host().GetProcessorFeature(KProcessorFeature_HWVirtEx);
1346
1347 if (fVTxAMDVSupported)
1348 iRowCount += 2; /* VT-x/AMD-V items. */
1349
1350 QString item = QString (sSectionItemTpl2).arg (tr ("Base Memory", "details report"),
1351 tr ("<nobr>%1 MB</nobr>", "details report"))
1352 .arg (aMachine.GetMemorySize())
1353 + QString (sSectionItemTpl2).arg (tr ("Processor(s)", "details report"),
1354 tr ("<nobr>%1</nobr>", "details report"))
1355 .arg (aMachine.GetCPUCount())
1356 + QString (sSectionItemTpl2).arg (tr ("Execution Cap", "details report"),
1357 tr ("<nobr>%1%</nobr>", "details report"))
1358 .arg (aMachine.GetCPUExecutionCap())
1359 + QString (sSectionItemTpl2).arg (tr ("Boot Order", "details report"), bootOrder)
1360#ifdef VBOX_WITH_FULL_DETAILS_REPORT
1361 + QString (sSectionItemTpl2).arg (tr ("ACPI", "details report"), acpi)
1362 + QString (sSectionItemTpl2).arg (tr ("IO APIC", "details report"), ioapic)
1363 + QString (sSectionItemTpl2).arg (tr ("PAE/NX", "details report"), pae)
1364#endif /* VBOX_WITH_FULL_DETAILS_REPORT */
1365 ;
1366
1367 if (fVTxAMDVSupported)
1368 item += QString (sSectionItemTpl2).arg (tr ("VT-x/AMD-V", "details report"), virt)
1369 + QString (sSectionItemTpl2).arg (tr ("Nested Paging", "details report"), nested);
1370
1371 report += sectionTpl
1372 .arg (2 + iRowCount) /* rows */
1373 .arg (":/chipset_16px.png", /* icon */
1374 "#system", /* link */
1375 tr ("System", "details report"), /* title */
1376 item); /* items */
1377 }
1378
1379 /* Display */
1380 {
1381 /* Rows including section header and footer */
1382 int rows = 2;
1383
1384 /* Video tab */
1385 QString item = QString(sSectionItemTpl2)
1386 .arg(tr ("Video Memory", "details report"),
1387 tr ("<nobr>%1 MB</nobr>", "details report"))
1388 .arg(aMachine.GetVRAMSize());
1389 ++rows;
1390
1391 int cGuestScreens = aMachine.GetMonitorCount();
1392 if (cGuestScreens > 1)
1393 {
1394 item += QString(sSectionItemTpl2)
1395 .arg(tr("Screens", "details report"))
1396 .arg(cGuestScreens);
1397 ++rows;
1398 }
1399
1400 QString acc3d = is3DAvailable() && aMachine.GetAccelerate3DEnabled()
1401 ? tr ("Enabled", "details report (3D Acceleration)")
1402 : tr ("Disabled", "details report (3D Acceleration)");
1403
1404 item += QString(sSectionItemTpl2)
1405 .arg(tr("3D Acceleration", "details report"), acc3d);
1406 ++rows;
1407
1408#ifdef VBOX_WITH_VIDEOHWACCEL
1409 QString acc2dVideo = aMachine.GetAccelerate2DVideoEnabled()
1410 ? tr ("Enabled", "details report (2D Video Acceleration)")
1411 : tr ("Disabled", "details report (2D Video Acceleration)");
1412
1413 item += QString (sSectionItemTpl2)
1414 .arg (tr ("2D Video Acceleration", "details report"), acc2dVideo);
1415 ++ rows;
1416#endif
1417
1418 /* VRDP tab */
1419 CVRDEServer srv = aMachine.GetVRDEServer();
1420 if (!srv.isNull())
1421 {
1422 if (srv.GetEnabled())
1423 item += QString (sSectionItemTpl2)
1424 .arg (tr ("Remote Desktop Server Port", "details report (VRDE Server)"))
1425 .arg (srv.GetVRDEProperty("TCP/Ports"));
1426 else
1427 item += QString (sSectionItemTpl2)
1428 .arg (tr ("Remote Desktop Server", "details report (VRDE Server)"))
1429 .arg (tr ("Disabled", "details report (VRDE Server)"));
1430 ++ rows;
1431 }
1432
1433 report += sectionTpl
1434 .arg (rows) /* rows */
1435 .arg (":/vrdp_16px.png", /* icon */
1436 "#display", /* link */
1437 tr ("Display", "details report"), /* title */
1438 item); /* items */
1439 }
1440
1441 /* Storage */
1442 {
1443 /* Rows including section header and footer */
1444 int rows = 2;
1445
1446 QString item;
1447
1448 /* Iterate over the all machine controllers: */
1449 CStorageControllerVector controllers = aMachine.GetStorageControllers();
1450 for (int i = 0; i < controllers.size(); ++i)
1451 {
1452 /* Get current controller: */
1453 const CStorageController &controller = controllers[i];
1454 /* Add controller information: */
1455 item += QString(sSectionItemTpl3).arg(controller.GetName());
1456 ++ rows;
1457
1458 /* Populate sorted map with attachments information: */
1459 QMap<StorageSlot,QString> attachmentsMap;
1460 CMediumAttachmentVector attachments = aMachine.GetMediumAttachmentsOfController(controller.GetName());
1461 for (int j = 0; j < attachments.size(); ++j)
1462 {
1463 /* Get current attachment: */
1464 const CMediumAttachment &attachment = attachments[j];
1465 /* Prepare current storage slot: */
1466 StorageSlot attachmentSlot(controller.GetBus(), attachment.GetPort(), attachment.GetDevice());
1467 /* Append 'device slot name' with 'device type name' for CD/DVD devices only: */
1468 QString strDeviceType = attachment.GetType() == KDeviceType_DVD ? tr("(CD/DVD)") : QString();
1469 if (!strDeviceType.isNull())
1470 strDeviceType.prepend(' ');
1471 /* Prepare current medium object: */
1472 const CMedium &medium = attachment.GetMedium();
1473 /* Prepare information about current medium & attachment: */
1474 QString strAttachmentInfo = !attachment.isOk() ? QString() :
1475 QString(sSectionItemTpl2)
1476 .arg(QString("&nbsp;&nbsp;") +
1477 gpConverter->toString(StorageSlot(controller.GetBus(),
1478 attachment.GetPort(),
1479 attachment.GetDevice())) + strDeviceType)
1480 .arg(details(medium, false));
1481 /* Insert that attachment into map: */
1482 if (!strAttachmentInfo.isNull())
1483 attachmentsMap.insert(attachmentSlot, strAttachmentInfo);
1484 }
1485
1486 /* Iterate over the sorted map with attachments information: */
1487 QMapIterator<StorageSlot,QString> it(attachmentsMap);
1488 while (it.hasNext())
1489 {
1490 /* Add controller information: */
1491 it.next();
1492 item += it.value();
1493 ++rows;
1494 }
1495 }
1496
1497 if (item.isNull())
1498 {
1499 item = QString (sSectionItemTpl1)
1500 .arg (tr ("Not Attached", "details report (Storage)"));
1501 ++ rows;
1502 }
1503
1504 report += sectionTpl
1505 .arg (rows) /* rows */
1506 .arg (":/attachment_16px.png", /* icon */
1507 "#storage", /* link */
1508 tr ("Storage", "details report"), /* title */
1509 item); /* items */
1510 }
1511
1512 /* Audio */
1513 {
1514 QString item;
1515
1516 CAudioAdapter audio = aMachine.GetAudioAdapter();
1517 int rows = audio.GetEnabled() ? 3 : 2;
1518 if (audio.GetEnabled())
1519 item = QString (sSectionItemTpl2)
1520 .arg (tr ("Host Driver", "details report (audio)"),
1521 gpConverter->toString (audio.GetAudioDriver())) +
1522 QString (sSectionItemTpl2)
1523 .arg (tr ("Controller", "details report (audio)"),
1524 gpConverter->toString (audio.GetAudioController()));
1525 else
1526 item = QString (sSectionItemTpl1)
1527 .arg (tr ("Disabled", "details report (audio)"));
1528
1529 report += sectionTpl
1530 .arg (rows + 1) /* rows */
1531 .arg (":/sound_16px.png", /* icon */
1532 "#audio", /* link */
1533 tr ("Audio", "details report"), /* title */
1534 item); /* items */
1535 }
1536
1537 /* Network */
1538 {
1539 QString item;
1540
1541 ulong count = mVBox.GetSystemProperties().GetMaxNetworkAdapters(KChipsetType_PIIX3);
1542 int rows = 2; /* including section header and footer */
1543 for (ulong slot = 0; slot < count; slot ++)
1544 {
1545 CNetworkAdapter adapter = aMachine.GetNetworkAdapter (slot);
1546 if (adapter.GetEnabled())
1547 {
1548 KNetworkAttachmentType type = adapter.GetAttachmentType();
1549 QString attType = gpConverter->toString (adapter.GetAdapterType())
1550 .replace (QRegExp ("\\s\\(.+\\)"), " (%1)");
1551 /* don't use the adapter type string for types that have
1552 * an additional symbolic network/interface name field, use
1553 * this name instead */
1554 if (type == KNetworkAttachmentType_Bridged)
1555 attType = attType.arg (tr ("Bridged adapter, %1",
1556 "details report (network)").arg (adapter.GetBridgedInterface()));
1557 else if (type == KNetworkAttachmentType_Internal)
1558 attType = attType.arg (tr ("Internal network, '%1'",
1559 "details report (network)").arg (adapter.GetInternalNetwork()));
1560 else if (type == KNetworkAttachmentType_HostOnly)
1561 attType = attType.arg (tr ("Host-only adapter, '%1'",
1562 "details report (network)").arg (adapter.GetHostOnlyInterface()));
1563 else if (type == KNetworkAttachmentType_Generic)
1564 attType = attType.arg (tr ("Generic, '%1'",
1565 "details report (network)").arg (adapter.GetGenericDriver()));
1566 else
1567 attType = attType.arg (gpConverter->toString (type));
1568
1569 item += QString (sSectionItemTpl2)
1570 .arg (tr ("Adapter %1", "details report (network)")
1571 .arg (adapter.GetSlot() + 1))
1572 .arg (attType);
1573 ++ rows;
1574 }
1575 }
1576 if (item.isNull())
1577 {
1578 item = QString (sSectionItemTpl1)
1579 .arg (tr ("Disabled", "details report (network)"));
1580 ++ rows;
1581 }
1582
1583 report += sectionTpl
1584 .arg (rows) /* rows */
1585 .arg (":/nw_16px.png", /* icon */
1586 "#network", /* link */
1587 tr ("Network", "details report"), /* title */
1588 item); /* items */
1589 }
1590
1591 /* Serial Ports */
1592 {
1593 QString item;
1594
1595 ulong count = mVBox.GetSystemProperties().GetSerialPortCount();
1596 int rows = 2; /* including section header and footer */
1597 for (ulong slot = 0; slot < count; slot ++)
1598 {
1599 CSerialPort port = aMachine.GetSerialPort (slot);
1600 if (port.GetEnabled())
1601 {
1602 KPortMode mode = port.GetHostMode();
1603 QString data =
1604 toCOMPortName (port.GetIRQ(), port.GetIOBase()) + ", ";
1605 if (mode == KPortMode_HostPipe ||
1606 mode == KPortMode_HostDevice ||
1607 mode == KPortMode_RawFile)
1608 data += QString ("%1 (<nobr>%2</nobr>)")
1609 .arg (gpConverter->toString (mode))
1610 .arg (QDir::toNativeSeparators (port.GetPath()));
1611 else
1612 data += gpConverter->toString (mode);
1613
1614 item += QString (sSectionItemTpl2)
1615 .arg (tr ("Port %1", "details report (serial ports)")
1616 .arg (port.GetSlot() + 1))
1617 .arg (data);
1618 ++ rows;
1619 }
1620 }
1621 if (item.isNull())
1622 {
1623 item = QString (sSectionItemTpl1)
1624 .arg (tr ("Disabled", "details report (serial ports)"));
1625 ++ rows;
1626 }
1627
1628 report += sectionTpl
1629 .arg (rows) /* rows */
1630 .arg (":/serial_port_16px.png", /* icon */
1631 "#serialPorts", /* link */
1632 tr ("Serial Ports", "details report"), /* title */
1633 item); /* items */
1634 }
1635
1636 /* Parallel Ports */
1637 {
1638 QString item;
1639
1640 ulong count = mVBox.GetSystemProperties().GetParallelPortCount();
1641 int rows = 2; /* including section header and footer */
1642 for (ulong slot = 0; slot < count; slot ++)
1643 {
1644 CParallelPort port = aMachine.GetParallelPort (slot);
1645 if (port.GetEnabled())
1646 {
1647 QString data =
1648 toLPTPortName (port.GetIRQ(), port.GetIOBase()) +
1649 QString (" (<nobr>%1</nobr>)")
1650 .arg (QDir::toNativeSeparators (port.GetPath()));
1651
1652 item += QString (sSectionItemTpl2)
1653 .arg (tr ("Port %1", "details report (parallel ports)")
1654 .arg (port.GetSlot() + 1))
1655 .arg (data);
1656 ++ rows;
1657 }
1658 }
1659 if (item.isNull())
1660 {
1661 item = QString (sSectionItemTpl1)
1662 .arg (tr ("Disabled", "details report (parallel ports)"));
1663 ++ rows;
1664 }
1665
1666 /* Temporary disabled */
1667 QString dummy = sectionTpl /* report += sectionTpl */
1668 .arg (rows) /* rows */
1669 .arg (":/parallel_port_16px.png", /* icon */
1670 "#parallelPorts", /* link */
1671 tr ("Parallel Ports", "details report"), /* title */
1672 item); /* items */
1673 }
1674
1675 /* USB */
1676 {
1677 QString item;
1678
1679 CUSBController ctl = aMachine.GetUSBController();
1680 if ( !ctl.isNull()
1681 && ctl.GetProxyAvailable())
1682 {
1683 /* the USB controller may be unavailable (i.e. in VirtualBox OSE) */
1684
1685 if (ctl.GetEnabled())
1686 {
1687 CUSBDeviceFilterVector coll = ctl.GetDeviceFilters();
1688 uint active = 0;
1689 for (int i = 0; i < coll.size(); ++i)
1690 if (coll[i].GetActive())
1691 active ++;
1692
1693 item = QString (sSectionItemTpl2)
1694 .arg (tr ("Device Filters", "details report (USB)"),
1695 tr ("%1 (%2 active)", "details report (USB)")
1696 .arg (coll.size()).arg (active));
1697 }
1698 else
1699 item = QString (sSectionItemTpl1)
1700 .arg (tr ("Disabled", "details report (USB)"));
1701
1702 report += sectionTpl
1703 .arg (2 + 1) /* rows */
1704 .arg (":/usb_16px.png", /* icon */
1705 "#usb", /* link */
1706 tr ("USB", "details report"), /* title */
1707 item); /* items */
1708 }
1709 }
1710
1711 /* Shared Folders */
1712 {
1713 QString item;
1714
1715 ulong count = aMachine.GetSharedFolders().size();
1716 if (count > 0)
1717 {
1718 item = QString (sSectionItemTpl2)
1719 .arg (tr ("Shared Folders", "details report (shared folders)"))
1720 .arg (count);
1721 }
1722 else
1723 item = QString (sSectionItemTpl1)
1724 .arg (tr ("None", "details report (shared folders)"));
1725
1726 report += sectionTpl
1727 .arg (2 + 1) /* rows */
1728 .arg (":/shared_folder_16px.png", /* icon */
1729 "#sfolders", /* link */
1730 tr ("Shared Folders", "details report"), /* title */
1731 item); /* items */
1732 }
1733
1734 return QString (sTableTpl). arg (report);
1735}
1736
1737#if defined(Q_WS_X11) && !defined(VBOX_OSE)
1738double VBoxGlobal::findLicenseFile (const QStringList &aFilesList, QRegExp aPattern, QString &aLicenseFile) const
1739{
1740 double maxVersionNumber = 0;
1741 aLicenseFile = "";
1742 for (int index = 0; index < aFilesList.count(); ++ index)
1743 {
1744 aPattern.indexIn (aFilesList [index]);
1745 QString version = aPattern.cap (1);
1746 if (maxVersionNumber < version.toDouble())
1747 {
1748 maxVersionNumber = version.toDouble();
1749 aLicenseFile = aFilesList [index];
1750 }
1751 }
1752 return maxVersionNumber;
1753}
1754
1755bool VBoxGlobal::showVirtualBoxLicense()
1756{
1757 /* get the apps doc path */
1758 int size = 256;
1759 char *buffer = (char*) RTMemTmpAlloc (size);
1760 RTPathAppDocs (buffer, size);
1761 QString path (buffer);
1762 RTMemTmpFree (buffer);
1763 QDir docDir (path);
1764 docDir.setFilter (QDir::Files);
1765 docDir.setNameFilters (QStringList ("License-*.html"));
1766
1767 /* Make sure that the language is in two letter code.
1768 * Note: if languageId() returns an empty string lang.name() will
1769 * return "C" which is an valid language code. */
1770 QLocale lang (VBoxGlobal::languageId());
1771
1772 QStringList filesList = docDir.entryList();
1773 QString licenseFile;
1774 /* First try to find a localized version of the license file. */
1775 double versionNumber = findLicenseFile (filesList, QRegExp (QString ("License-([\\d\\.]+)-%1.html").arg (lang.name())), licenseFile);
1776 /* If there wasn't a localized version of the currently selected language,
1777 * search for the generic one. */
1778 if (versionNumber == 0)
1779 versionNumber = findLicenseFile (filesList, QRegExp ("License-([\\d\\.]+).html"), licenseFile);
1780 /* Check the version again. */
1781 if (!versionNumber)
1782 {
1783 msgCenter().cannotFindLicenseFiles (path);
1784 return false;
1785 }
1786
1787 /* compose the latest license file full path */
1788 QString latestVersion = QString::number (versionNumber);
1789 QString latestFilePath = docDir.absoluteFilePath (licenseFile);
1790
1791 /* check for the agreed license version */
1792 QStringList strList = virtualBox().GetExtraData (GUI_LicenseKey).split(",");
1793 for (int i=0; i < strList.size(); ++i)
1794 if (strList.at(i) == latestVersion)
1795 return true;
1796
1797 VBoxLicenseViewer licenseDialog;
1798 bool result = licenseDialog.showLicenseFromFile(latestFilePath) == QDialog::Accepted;
1799 if (result)
1800 virtualBox().SetExtraData (GUI_LicenseKey, (strList << latestVersion).join(","));
1801 return result;
1802}
1803#endif /* defined(Q_WS_X11) && !defined(VBOX_OSE) */
1804
1805/**
1806 * Opens a direct session for a machine with the given ID.
1807 * This method does user-friendly error handling (display error messages, etc.).
1808 * and returns a null CSession object in case of any error.
1809 * If this method succeeds, don't forget to close the returned session when
1810 * it is no more necessary.
1811 *
1812 * @param aId Machine ID.
1813 * @param aLockType @c KLockType_Shared to open an existing session with
1814 * the machine which is already running, @c KLockType_Write
1815 * to open a new direct session, @c KLockType_VM to open
1816 * a new session for running a VM in this process.
1817 */
1818CSession VBoxGlobal::openSession(const QString &aId, KLockType aLockType /* = KLockType_Shared */)
1819{
1820 CSession session;
1821 session.createInstance(CLSID_Session);
1822 if (session.isNull())
1823 {
1824 msgCenter().cannotOpenSession (session);
1825 return session;
1826 }
1827
1828 CMachine foundMachine = CVirtualBox(mVBox).FindMachine(aId);
1829 if (!foundMachine.isNull())
1830 {
1831 foundMachine.LockMachine(session, aLockType);
1832 if (session.GetType() == KSessionType_Shared)
1833 {
1834 CMachine machine = session.GetMachine();
1835 /* Make sure that the language is in two letter code.
1836 * Note: if languageId() returns an empty string lang.name() will
1837 * return "C" which is an valid language code. */
1838 QLocale lang(VBoxGlobal::languageId());
1839 machine.SetGuestPropertyValue ("/VirtualBox/HostInfo/GUI/LanguageID", lang.name());
1840 }
1841 }
1842
1843 if (!foundMachine.isOk())
1844 {
1845 msgCenter().cannotOpenSession(foundMachine);
1846 session.detach();
1847 }
1848 else if (!mVBox.isOk())
1849 {
1850 msgCenter().cannotOpenSession(mVBox, foundMachine);
1851 session.detach();
1852 }
1853
1854 return session;
1855}
1856
1857/**
1858 * Appends the NULL medium to the media list.
1859 * For using with VBoxGlobal::startEnumeratingMedia() only.
1860 */
1861static void addNullMediumToList (VBoxMediaList &aList, VBoxMediaList::iterator aWhere)
1862{
1863 UIMedium medium;
1864 aList.insert (aWhere, medium);
1865}
1866
1867/**
1868 * Appends the given list of mediums to the media list.
1869 * For using with VBoxGlobal::startEnumeratingMedia() only.
1870 */
1871static void addMediumsToList (const CMediumVector &aVector,
1872 VBoxMediaList &aList,
1873 VBoxMediaList::iterator aWhere,
1874 UIMediumType aType,
1875 UIMedium *aParent = 0)
1876{
1877 VBoxMediaList::iterator first = aWhere;
1878
1879 for (CMediumVector::ConstIterator it = aVector.begin(); it != aVector.end(); ++ it)
1880 {
1881 CMedium cmedium (*it);
1882 UIMedium medium (cmedium, aType, aParent);
1883
1884 /* Search for a proper alphabetic position */
1885 VBoxMediaList::iterator jt = first;
1886 for (; jt != aWhere; ++ jt)
1887 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
1888 break;
1889
1890 aList.insert (jt, medium);
1891
1892 /* Adjust the first item if inserted before it */
1893 if (jt == first)
1894 -- first;
1895 }
1896}
1897
1898/**
1899 * Appends the given list of hard disks and all their children to the media list.
1900 * For using with VBoxGlobal::startEnumeratingMedia() only.
1901 */
1902static void addHardDisksToList (const CMediumVector &aVector,
1903 VBoxMediaList &aList,
1904 VBoxMediaList::iterator aWhere,
1905 UIMedium *aParent = 0)
1906{
1907 VBoxMediaList::iterator first = aWhere;
1908
1909 /* First pass: Add siblings sorted */
1910 for (CMediumVector::ConstIterator it = aVector.begin(); it != aVector.end(); ++ it)
1911 {
1912 CMedium cmedium (*it);
1913 UIMedium medium (cmedium, UIMediumType_HardDisk, aParent);
1914
1915 /* Search for a proper alphabetic position */
1916 VBoxMediaList::iterator jt = first;
1917 for (; jt != aWhere; ++ jt)
1918 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
1919 break;
1920
1921 aList.insert (jt, medium);
1922
1923 /* Adjust the first item if inserted before it */
1924 if (jt == first)
1925 -- first;
1926 }
1927
1928 /* Second pass: Add children */
1929 for (VBoxMediaList::iterator it = first; it != aWhere;)
1930 {
1931 CMediumVector children = (*it).medium().GetChildren();
1932 UIMedium *parent = &(*it);
1933
1934 ++ it; /* go to the next sibling before inserting children */
1935 addHardDisksToList (children, aList, it, parent);
1936 }
1937}
1938
1939/**
1940 * Starts a thread that asynchronously enumerates all currently registered
1941 * media.
1942 *
1943 * Before the enumeration is started, the current media list (a list returned by
1944 * #currentMediaList()) is populated with all registered media and the
1945 * #mediumEnumStarted() signal is emitted. The enumeration thread then walks this
1946 * list, checks for media accessibility and emits #mediumEnumerated() signals of
1947 * each checked medium. When all media are checked, the enumeration thread is
1948 * stopped and the #mediumEnumFinished() signal is emitted.
1949 *
1950 * If the enumeration is already in progress, no new thread is started.
1951 *
1952 * The media list returned by #currentMediaList() is always sorted
1953 * alphabetically by the location attribute and comes in the following order:
1954 * <ol>
1955 * <li>All hard disks. If a hard disk has children, these children
1956 * (alphabetically sorted) immediately follow their parent and therefore
1957 * appear before its next sibling hard disk.</li>
1958 * <li>All CD/DVD images.</li>
1959 * <li>All Floppy images.</li>
1960 * </ol>
1961 *
1962 * Note that #mediumEnumerated() signals are emitted in the same order as
1963 * described above.
1964 *
1965 * @sa #currentMediaList()
1966 * @sa #isMediaEnumerationStarted()
1967 */
1968void VBoxGlobal::startEnumeratingMedia()
1969{
1970 AssertReturnVoid (mValid);
1971
1972 /* check if already started but not yet finished */
1973 if (mMediaEnumThread != NULL)
1974 return;
1975
1976 /* ignore the request during application termination */
1977 if (sVBoxGlobalInCleanup)
1978 return;
1979
1980 /* composes a list of all currently known media & their children */
1981 mMediaList.clear();
1982 addNullMediumToList (mMediaList, mMediaList.end());
1983 addHardDisksToList (mVBox.GetHardDisks(), mMediaList, mMediaList.end());
1984 addMediumsToList (mHost.GetDVDDrives(), mMediaList, mMediaList.end(), UIMediumType_DVD);
1985 addMediumsToList (mVBox.GetDVDImages(), mMediaList, mMediaList.end(), UIMediumType_DVD);
1986 addMediumsToList (mHost.GetFloppyDrives(), mMediaList, mMediaList.end(), UIMediumType_Floppy);
1987 addMediumsToList (mVBox.GetFloppyImages(), mMediaList, mMediaList.end(), UIMediumType_Floppy);
1988
1989 /* enumeration thread class */
1990 class MediaEnumThread : public QThread
1991 {
1992 public:
1993
1994 MediaEnumThread (VBoxMediaList &aList)
1995 : mVector (aList.size())
1996 , mSavedIt (aList.begin())
1997 {
1998 int i = 0;
1999 for (VBoxMediaList::const_iterator it = aList.begin();
2000 it != aList.end(); ++ it)
2001 mVector [i ++] = *it;
2002 }
2003
2004 virtual void run()
2005 {
2006 LogFlow (("MediaEnumThread started.\n"));
2007 COMBase::InitializeCOM(false);
2008
2009 CVirtualBox mVBox = vboxGlobal().virtualBox();
2010 QObject *self = &vboxGlobal();
2011
2012 /* Enumerate the list */
2013 for (int i = 0; i < mVector.size() && !sVBoxGlobalInCleanup; ++ i)
2014 {
2015 mVector [i].blockAndQueryState();
2016 QApplication::
2017 postEvent (self,
2018 new VBoxMediaEnumEvent (mVector [i], mSavedIt));
2019 ++mSavedIt;
2020 }
2021
2022 /* Post the end-of-enumeration event */
2023 if (!sVBoxGlobalInCleanup)
2024 QApplication::postEvent (self, new VBoxMediaEnumEvent (mSavedIt));
2025
2026 COMBase::CleanupCOM();
2027 LogFlow (("MediaEnumThread finished.\n"));
2028 }
2029
2030 private:
2031
2032 QVector <UIMedium> mVector;
2033 VBoxMediaList::iterator mSavedIt;
2034 };
2035
2036 mMediaEnumThread = new MediaEnumThread (mMediaList);
2037 AssertReturnVoid (mMediaEnumThread);
2038
2039 /* emit mediumEnumStarted() after we set mMediaEnumThread to != NULL
2040 * to cause isMediaEnumerationStarted() to return TRUE from slots */
2041 emit mediumEnumStarted();
2042
2043 mMediaEnumThread->start();
2044}
2045
2046void VBoxGlobal::reloadProxySettings()
2047{
2048 UIProxyManager proxyManager(settings().proxySettings());
2049 if (proxyManager.proxyEnabled())
2050 {
2051 QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::HttpProxy,
2052 proxyManager.proxyHost(),
2053 proxyManager.proxyPort().toInt(),
2054 proxyManager.authEnabled() ? proxyManager.authLogin() : QString(),
2055 proxyManager.authEnabled() ? proxyManager.authPassword() : QString()));
2056 }
2057 else
2058 {
2059 QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::NoProxy));
2060 }
2061}
2062
2063/**
2064 * Adds a new medium to the current media list and emits the #mediumAdded()
2065 * signal.
2066 *
2067 * @sa #currentMediaList()
2068 */
2069void VBoxGlobal::addMedium (const UIMedium &aMedium)
2070{
2071 /* Note that we maintain the same order here as #startEnumeratingMedia() */
2072
2073 VBoxMediaList::iterator it = mMediaList.begin();
2074
2075 if (aMedium.type() == UIMediumType_HardDisk)
2076 {
2077 VBoxMediaList::iterator itParent = mMediaList.end();
2078
2079 for (; it != mMediaList.end(); ++ it)
2080 {
2081 /* skip null medium that come first */
2082 if ((*it).isNull()) continue;
2083
2084 if ((*it).type() != UIMediumType_HardDisk)
2085 break;
2086
2087 if (aMedium.parent() != NULL && itParent == mMediaList.end())
2088 {
2089 if (&*it == aMedium.parent())
2090 itParent = it;
2091 }
2092 else
2093 {
2094 /* break if met a parent's sibling (will insert before it) */
2095 if (aMedium.parent() != NULL &&
2096 (*it).parent() == (*itParent).parent())
2097 break;
2098
2099 /* compare to aMedium's siblings */
2100 if ((*it).parent() == aMedium.parent() &&
2101 (*it).name().localeAwareCompare (aMedium.name()) > 0)
2102 break;
2103 }
2104 }
2105
2106 AssertReturnVoid (aMedium.parent() == NULL || itParent != mMediaList.end());
2107 }
2108 else
2109 {
2110 for (; it != mMediaList.end(); ++ it)
2111 {
2112 /* skip null medium that come first */
2113 if ((*it).isNull()) continue;
2114
2115 /* skip HardDisks that come first */
2116 if ((*it).type() == UIMediumType_HardDisk)
2117 continue;
2118
2119 /* skip DVD when inserting Floppy */
2120 if (aMedium.type() == UIMediumType_Floppy &&
2121 (*it).type() == UIMediumType_DVD)
2122 continue;
2123
2124 if ((*it).name().localeAwareCompare (aMedium.name()) > 0 ||
2125 (aMedium.type() == UIMediumType_DVD &&
2126 (*it).type() == UIMediumType_Floppy))
2127 break;
2128 }
2129 }
2130
2131 it = mMediaList.insert (it, aMedium);
2132
2133 emit mediumAdded (*it);
2134}
2135
2136/**
2137 * Updates the medium in the current media list and emits the #mediumUpdated()
2138 * signal.
2139 *
2140 * @sa #currentMediaList()
2141 */
2142void VBoxGlobal::updateMedium (const UIMedium &aMedium)
2143{
2144 VBoxMediaList::Iterator it;
2145 for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2146 if ((*it).id() == aMedium.id())
2147 break;
2148
2149 AssertReturnVoid (it != mMediaList.end());
2150
2151 if (&*it != &aMedium)
2152 *it = aMedium;
2153
2154 emit mediumUpdated (*it);
2155}
2156
2157/**
2158 * Removes the medium from the current media list and emits the #mediumRemoved()
2159 * signal.
2160 *
2161 * @sa #currentMediaList()
2162 */
2163void VBoxGlobal::removeMedium (UIMediumType aType, const QString &aId)
2164{
2165 VBoxMediaList::Iterator it;
2166 for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2167 if ((*it).id() == aId)
2168 break;
2169
2170 AssertReturnVoid (it != mMediaList.end());
2171
2172#if DEBUG
2173 /* sanity: must be no children */
2174 {
2175 VBoxMediaList::Iterator jt = it;
2176 ++ jt;
2177 AssertReturnVoid (jt == mMediaList.end() || (*jt).parent() != &*it);
2178 }
2179#endif
2180
2181 UIMedium *pParent = (*it).parent();
2182
2183 /* remove the medium from the list to keep it in sync with the server "for
2184 * free" when the medium is deleted from one of our UIs */
2185 mMediaList.erase (it);
2186
2187 emit mediumRemoved (aType, aId);
2188
2189 /* also emit the parent update signal because some attributes like
2190 * isReadOnly() may have been changed after child removal */
2191 if (pParent != NULL)
2192 {
2193 pParent->refresh();
2194 emit mediumUpdated (*pParent);
2195 }
2196}
2197
2198/**
2199 * Searches for a VBoxMedum object representing the given COM medium object.
2200 *
2201 * @return true if found and false otherwise.
2202 */
2203bool VBoxGlobal::findMedium (const CMedium &aObj, UIMedium &aMedium) const
2204{
2205 for (VBoxMediaList::ConstIterator it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2206 {
2207 if (((*it).medium().isNull() && aObj.isNull()) ||
2208 (!(*it).medium().isNull() && !aObj.isNull() && (*it).medium().GetId() == aObj.GetId()))
2209 {
2210 aMedium = (*it);
2211 return true;
2212 }
2213 }
2214 return false;
2215}
2216
2217/**
2218 * Searches for a VBoxMedum object with the given medium id attribute.
2219 *
2220 * @return VBoxMedum if found which is invalid otherwise.
2221 */
2222UIMedium VBoxGlobal::findMedium (const QString &aMediumId) const
2223{
2224 for (VBoxMediaList::ConstIterator it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2225 if ((*it).id() == aMediumId)
2226 return *it;
2227 return UIMedium();
2228}
2229
2230/* Open some external medium using file open dialog
2231 * and temporary cache (enumerate) it in GUI inner mediums cache: */
2232QString VBoxGlobal::openMediumWithFileOpenDialog(UIMediumType mediumType, QWidget *pParent,
2233 const QString &strDefaultFolder /* = QString() */,
2234 bool fUseLastFolder /* = false */)
2235{
2236 /* Initialize variables: */
2237 QList < QPair <QString, QString> > filters;
2238 QStringList backends;
2239 QStringList prefixes;
2240 QString strFilter;
2241 QString strTitle;
2242 QString allType;
2243 QString strLastFolder;
2244 switch (mediumType)
2245 {
2246 case UIMediumType_HardDisk:
2247 {
2248 filters = vboxGlobal().HDDBackends();
2249 strTitle = tr("Please choose a virtual hard drive file");
2250 allType = tr("All virtual hard drive files (%1)");
2251 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderHD);
2252 if (strLastFolder.isEmpty())
2253 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderCD);
2254 if (strLastFolder.isEmpty())
2255 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderFD);
2256 break;
2257 }
2258 case UIMediumType_DVD:
2259 {
2260 filters = vboxGlobal().DVDBackends();
2261 strTitle = tr("Please choose a virtual optical disk file");
2262 allType = tr("All virtual optical disk files (%1)");
2263 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderCD);
2264 if (strLastFolder.isEmpty())
2265 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderHD);
2266 if (strLastFolder.isEmpty())
2267 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderFD);
2268 break;
2269 }
2270 case UIMediumType_Floppy:
2271 {
2272 filters = vboxGlobal().FloppyBackends();
2273 strTitle = tr("Please choose a virtual floppy disk file");
2274 allType = tr("All virtual floppy disk files (%1)");
2275 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderFD);
2276 if (strLastFolder.isEmpty())
2277 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderCD);
2278 if (strLastFolder.isEmpty())
2279 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderHD);
2280 break;
2281 }
2282 default:
2283 break;
2284 }
2285 QString strHomeFolder = fUseLastFolder && !strLastFolder.isEmpty() ? strLastFolder :
2286 strDefaultFolder.isEmpty() ? vboxGlobal().virtualBox().GetHomeFolder() : strDefaultFolder;
2287
2288 /* Prepare filters and backends: */
2289 for (int i = 0; i < filters.count(); ++i)
2290 {
2291 /* Get iterated filter: */
2292 QPair <QString, QString> item = filters.at(i);
2293 /* Create one backend filter string: */
2294 backends << QString("%1 (%2)").arg(item.first).arg(item.second);
2295 /* Save the suffix's for the "All" entry: */
2296 prefixes << item.second;
2297 }
2298 if (!prefixes.isEmpty())
2299 backends.insert(0, allType.arg(prefixes.join(" ").trimmed()));
2300 backends << tr("All files (*)");
2301 strFilter = backends.join(";;").trimmed();
2302
2303 /* Create open file dialog: */
2304 QStringList files = QIFileDialog::getOpenFileNames(strHomeFolder, strFilter, pParent, strTitle, 0, true, true);
2305
2306 /* If dialog has some result: */
2307 if (!files.empty() && !files[0].isEmpty())
2308 return openMedium(mediumType, files[0], pParent);
2309
2310 return QString();
2311}
2312
2313QString VBoxGlobal::openMedium(UIMediumType mediumType, QString strMediumLocation, QWidget *pParent /* = 0*/)
2314{
2315 /* Convert to native separators: */
2316 strMediumLocation = QDir::toNativeSeparators(strMediumLocation);
2317
2318 /* Initialize variables: */
2319 CVirtualBox vbox = vboxGlobal().virtualBox();
2320
2321 /* Remember the path of the last chosen medium: */
2322 QString strRecentFolderKey = mediumType == UIMediumType_HardDisk ? GUI_RecentFolderHD :
2323 mediumType == UIMediumType_DVD ? GUI_RecentFolderCD :
2324 mediumType == UIMediumType_Floppy ? GUI_RecentFolderFD :
2325 QString();
2326 vbox.SetExtraData(strRecentFolderKey, QFileInfo(strMediumLocation).absolutePath());
2327
2328 /* Update recently used list: */
2329 QString strRecentListKey = mediumType == UIMediumType_HardDisk ? GUI_RecentListHD :
2330 mediumType == UIMediumType_DVD ? GUI_RecentListCD :
2331 mediumType == UIMediumType_Floppy ? GUI_RecentListFD :
2332 QString();
2333 QStringList recentMediumList = vbox.GetExtraData(strRecentListKey).split(';');
2334 if (recentMediumList.contains(strMediumLocation))
2335 recentMediumList.removeAll(strMediumLocation);
2336 recentMediumList.prepend(strMediumLocation);
2337 while(recentMediumList.size() > 5) recentMediumList.removeLast();
2338 vbox.SetExtraData(strRecentListKey, recentMediumList.join(";"));
2339
2340 /* Open corresponding medium: */
2341 CMedium comMedium = vbox.OpenMedium(strMediumLocation, mediumTypeToGlobal(mediumType), KAccessMode_ReadWrite, false);
2342
2343 if (vbox.isOk())
2344 {
2345 /* Prepare vbox medium wrapper: */
2346 UIMedium vboxMedium;
2347
2348 /* First of all we should test if that medium already opened: */
2349 if (!vboxGlobal().findMedium(comMedium, vboxMedium))
2350 {
2351 /* And create new otherwise: */
2352 vboxMedium = UIMedium(CMedium(comMedium), mediumType, KMediumState_Created);
2353 vboxGlobal().addMedium(vboxMedium);
2354 }
2355
2356 /* Return vboxMedium id: */
2357 return vboxMedium.id();
2358 }
2359 else
2360 msgCenter().cannotOpenMedium(pParent, vbox, mediumType, strMediumLocation);
2361
2362 return QString();
2363}
2364
2365#ifdef VBOX_GUI_WITH_SYSTRAY
2366/**
2367 * Returns the number of current running Fe/Qt4 main windows.
2368 *
2369 * @return Number of running main windows.
2370 */
2371int VBoxGlobal::mainWindowCount ()
2372{
2373 return mVBox.GetExtraData (GUI_MainWindowCount).toInt();
2374}
2375#endif
2376
2377/**
2378 * Native language name of the currently installed translation.
2379 * Returns "English" if no translation is installed
2380 * or if the translation file is invalid.
2381 */
2382QString VBoxGlobal::languageName() const
2383{
2384
2385 return qApp->translate ("@@@", "English",
2386 "Native language name");
2387}
2388
2389/**
2390 * Native language country name of the currently installed translation.
2391 * Returns "--" if no translation is installed or if the translation file is
2392 * invalid, or if the language is independent on the country.
2393 */
2394QString VBoxGlobal::languageCountry() const
2395{
2396 return qApp->translate ("@@@", "--",
2397 "Native language country name "
2398 "(empty if this language is for all countries)");
2399}
2400
2401/**
2402 * Language name of the currently installed translation, in English.
2403 * Returns "English" if no translation is installed
2404 * or if the translation file is invalid.
2405 */
2406QString VBoxGlobal::languageNameEnglish() const
2407{
2408
2409 return qApp->translate ("@@@", "English",
2410 "Language name, in English");
2411}
2412
2413/**
2414 * Language country name of the currently installed translation, in English.
2415 * Returns "--" if no translation is installed or if the translation file is
2416 * invalid, or if the language is independent on the country.
2417 */
2418QString VBoxGlobal::languageCountryEnglish() const
2419{
2420 return qApp->translate ("@@@", "--",
2421 "Language country name, in English "
2422 "(empty if native country name is empty)");
2423}
2424
2425/**
2426 * Comma-separated list of authors of the currently installed translation.
2427 * Returns "Oracle Corporation" if no translation is installed or if the
2428 * translation file is invalid, or if the translation is supplied by Oracle
2429 * Corporation
2430 */
2431QString VBoxGlobal::languageTranslators() const
2432{
2433 return qApp->translate ("@@@", "Oracle Corporation",
2434 "Comma-separated list of translators");
2435}
2436
2437/**
2438 * Changes the language of all global string constants according to the
2439 * currently installed translations tables.
2440 */
2441void VBoxGlobal::retranslateUi()
2442{
2443 mDiskTypes_Differencing = tr ("Differencing", "DiskType");
2444
2445 mUserDefinedPortName = tr ("User-defined", "serial port");
2446
2447 mWarningIcon = UIIconPool::defaultIcon(UIIconPool::MessageBoxWarningIcon).pixmap (16, 16);
2448 Assert (!mWarningIcon.isNull());
2449
2450 mErrorIcon = UIIconPool::defaultIcon(UIIconPool::MessageBoxCriticalIcon).pixmap (16, 16);
2451 Assert (!mErrorIcon.isNull());
2452
2453 /* refresh media properties since they contain some translations too */
2454 for (VBoxMediaList::iterator it = mMediaList.begin();
2455 it != mMediaList.end(); ++ it)
2456 it->refresh();
2457
2458#ifdef Q_WS_X11
2459 /* As X11 do not have functionality for providing human readable key names,
2460 * we keep a table of them, which must be updated when the language is changed. */
2461 UIHotKey::retranslateKeyNames();
2462#endif /* Q_WS_X11 */
2463}
2464
2465// public static stuff
2466////////////////////////////////////////////////////////////////////////////////
2467
2468/* static */
2469bool VBoxGlobal::isDOSType (const QString &aOSTypeId)
2470{
2471 if (aOSTypeId.left (3) == "dos" ||
2472 aOSTypeId.left (3) == "win" ||
2473 aOSTypeId.left (3) == "os2")
2474 return true;
2475
2476 return false;
2477}
2478
2479const char *gVBoxLangSubDir = "/nls";
2480const char *gVBoxLangFileBase = "VirtualBox_";
2481const char *gVBoxLangFileExt = ".qm";
2482const char *gVBoxLangIDRegExp = "(([a-z]{2})(?:_([A-Z]{2}))?)|(C)";
2483const char *gVBoxBuiltInLangName = "C";
2484
2485class VBoxTranslator : public QTranslator
2486{
2487public:
2488
2489 VBoxTranslator (QObject *aParent = 0)
2490 : QTranslator (aParent) {}
2491
2492 bool loadFile (const QString &aFileName)
2493 {
2494 QFile file (aFileName);
2495 if (!file.open (QIODevice::ReadOnly))
2496 return false;
2497 mData = file.readAll();
2498 return load ((uchar*) mData.data(), mData.size());
2499 }
2500
2501private:
2502
2503 QByteArray mData;
2504};
2505
2506static VBoxTranslator *sTranslator = 0;
2507static QString sLoadedLangId = gVBoxBuiltInLangName;
2508
2509/**
2510 * Returns the loaded (active) language ID.
2511 * Note that it may not match with VBoxGlobalSettings::languageId() if the
2512 * specified language cannot be loaded.
2513 * If the built-in language is active, this method returns "C".
2514 *
2515 * @note "C" is treated as the built-in language for simplicity -- the C
2516 * locale is used in unix environments as a fallback when the requested
2517 * locale is invalid. This way we don't need to process both the "built_in"
2518 * language and the "C" language (which is a valid environment setting)
2519 * separately.
2520 */
2521/* static */
2522QString VBoxGlobal::languageId()
2523{
2524 return sLoadedLangId;
2525}
2526
2527/**
2528 * Loads the language by language ID.
2529 *
2530 * @param aLangId Language ID in in form of xx_YY. QString::null means the
2531 * system default language.
2532 */
2533/* static */
2534void VBoxGlobal::loadLanguage (const QString &aLangId)
2535{
2536 QString langId = aLangId.isEmpty() ?
2537 VBoxGlobal::systemLanguageId() : aLangId;
2538 QString languageFileName;
2539 QString selectedLangId = gVBoxBuiltInLangName;
2540
2541 /* If C is selected we change it temporary to en. This makes sure any extra
2542 * "en" translation file will be loaded. This is necessary for loading the
2543 * plural forms of some of our translations. */
2544 bool fResetToC = false;
2545 if (langId == "C")
2546 {
2547 langId = "en";
2548 fResetToC = true;
2549 }
2550
2551 char szNlsPath[RTPATH_MAX];
2552 int rc;
2553
2554 rc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
2555 AssertRC (rc);
2556
2557 QString nlsPath = QString(szNlsPath) + gVBoxLangSubDir;
2558 QDir nlsDir (nlsPath);
2559
2560 Assert (!langId.isEmpty());
2561 if (!langId.isEmpty() && langId != gVBoxBuiltInLangName)
2562 {
2563 QRegExp regExp (gVBoxLangIDRegExp);
2564 int pos = regExp.indexIn (langId);
2565 /* the language ID should match the regexp completely */
2566 AssertReturnVoid (pos == 0);
2567
2568 QString lang = regExp.cap (2);
2569
2570 if (nlsDir.exists (gVBoxLangFileBase + langId + gVBoxLangFileExt))
2571 {
2572 languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + langId +
2573 gVBoxLangFileExt);
2574 selectedLangId = langId;
2575 }
2576 else if (nlsDir.exists (gVBoxLangFileBase + lang + gVBoxLangFileExt))
2577 {
2578 languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + lang +
2579 gVBoxLangFileExt);
2580 selectedLangId = lang;
2581 }
2582 else
2583 {
2584 /* Never complain when the default language is requested. In any
2585 * case, if no explicit language file exists, we will simply
2586 * fall-back to English (built-in). */
2587 if (!aLangId.isNull() && langId != "en")
2588 msgCenter().cannotFindLanguage (langId, nlsPath);
2589 /* selectedLangId remains built-in here */
2590 AssertReturnVoid (selectedLangId == gVBoxBuiltInLangName);
2591 }
2592 }
2593
2594 /* delete the old translator if there is one */
2595 if (sTranslator)
2596 {
2597 /* QTranslator destructor will call qApp->removeTranslator() for
2598 * us. It will also delete all its child translations we attach to it
2599 * below, so we don't have to care about them specially. */
2600 delete sTranslator;
2601 }
2602
2603 /* load new language files */
2604 sTranslator = new VBoxTranslator (qApp);
2605 Assert (sTranslator);
2606 bool loadOk = true;
2607 if (sTranslator)
2608 {
2609 if (selectedLangId != gVBoxBuiltInLangName)
2610 {
2611 Assert (!languageFileName.isNull());
2612 loadOk = sTranslator->loadFile (languageFileName);
2613 }
2614 /* we install the translator in any case: on failure, this will
2615 * activate an empty translator that will give us English
2616 * (built-in) */
2617 qApp->installTranslator (sTranslator);
2618 }
2619 else
2620 loadOk = false;
2621
2622 if (loadOk)
2623 sLoadedLangId = selectedLangId;
2624 else
2625 {
2626 msgCenter().cannotLoadLanguage (languageFileName);
2627 sLoadedLangId = gVBoxBuiltInLangName;
2628 }
2629
2630 /* Try to load the corresponding Qt translation */
2631 if (sLoadedLangId != gVBoxBuiltInLangName)
2632 {
2633#ifdef Q_OS_UNIX
2634 /* We use system installations of Qt on Linux systems, so first, try
2635 * to load the Qt translation from the system location. */
2636 languageFileName = QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" +
2637 sLoadedLangId + gVBoxLangFileExt;
2638 QTranslator *qtSysTr = new QTranslator (sTranslator);
2639 Assert (qtSysTr);
2640 if (qtSysTr && qtSysTr->load (languageFileName))
2641 qApp->installTranslator (qtSysTr);
2642 /* Note that the Qt translation supplied by Oracle is always loaded
2643 * afterwards to make sure it will take precedence over the system
2644 * translation (it may contain more decent variants of translation
2645 * that better correspond to VirtualBox UI). We need to load both
2646 * because a newer version of Qt may be installed on the user computer
2647 * and the Oracle version may not fully support it. We don't do it on
2648 * Win32 because we supply a Qt library there and therefore the
2649 * Oracle translation is always the best one. */
2650#endif
2651 languageFileName = nlsDir.absoluteFilePath (QString ("qt_") +
2652 sLoadedLangId +
2653 gVBoxLangFileExt);
2654 QTranslator *qtTr = new QTranslator (sTranslator);
2655 Assert (qtTr);
2656 if (qtTr && (loadOk = qtTr->load (languageFileName)))
2657 qApp->installTranslator (qtTr);
2658 /* The below message doesn't fit 100% (because it's an additional
2659 * language and the main one won't be reset to built-in on failure)
2660 * but the load failure is so rare here that it's not worth a separate
2661 * message (but still, having something is better than having none) */
2662 if (!loadOk && !aLangId.isNull())
2663 msgCenter().cannotLoadLanguage (languageFileName);
2664 }
2665 if (fResetToC)
2666 sLoadedLangId = "C";
2667#ifdef Q_WS_MAC
2668 /* Qt doesn't translate the items in the Application menu initially.
2669 * Manually trigger an update. */
2670 ::darwinRetranslateAppMenu();
2671#endif /* Q_WS_MAC */
2672}
2673
2674QString VBoxGlobal::helpFile() const
2675{
2676#if defined (Q_WS_WIN32)
2677 const QString name = "VirtualBox";
2678 const QString suffix = "chm";
2679#elif defined (Q_WS_MAC)
2680 const QString name = "UserManual";
2681 const QString suffix = "pdf";
2682#elif defined (Q_WS_X11)
2683# if defined VBOX_OSE
2684 const QString name = "UserManual";
2685 const QString suffix = "pdf";
2686# else
2687 const QString name = "VirtualBox";
2688 const QString suffix = "chm";
2689# endif
2690#endif
2691 /* Where are the docs located? */
2692 char szDocsPath[RTPATH_MAX];
2693 int rc = RTPathAppDocs (szDocsPath, sizeof (szDocsPath));
2694 AssertRC (rc);
2695 /* Make sure that the language is in two letter code.
2696 * Note: if languageId() returns an empty string lang.name() will
2697 * return "C" which is an valid language code. */
2698 QLocale lang (VBoxGlobal::languageId());
2699
2700 /* Construct the path and the filename */
2701 QString manual = QString ("%1/%2_%3.%4").arg (szDocsPath)
2702 .arg (name)
2703 .arg (lang.name())
2704 .arg (suffix);
2705 /* Check if a help file with that name exists */
2706 QFileInfo fi (manual);
2707 if (fi.exists())
2708 return manual;
2709
2710 /* Fall back to the standard */
2711 manual = QString ("%1/%2.%4").arg (szDocsPath)
2712 .arg (name)
2713 .arg (suffix);
2714 return manual;
2715}
2716
2717/**
2718 * Replacement for QToolButton::setTextLabel() that handles the shortcut
2719 * letter (if it is present in the argument string) as if it were a setText()
2720 * call: the shortcut letter is used to automatically assign an "Alt+<letter>"
2721 * accelerator key sequence to the given tool button.
2722 *
2723 * @note This method preserves the icon set if it was assigned before. Only
2724 * the text label and the accelerator are changed.
2725 *
2726 * @param aToolButton Tool button to set the text label on.
2727 * @param aTextLabel Text label to set.
2728 */
2729/* static */
2730void VBoxGlobal::setTextLabel (QToolButton *aToolButton,
2731 const QString &aTextLabel)
2732{
2733 AssertReturnVoid (aToolButton != NULL);
2734
2735 /* remember the icon set as setText() will kill it */
2736 QIcon iset = aToolButton->icon();
2737 /* re-use the setText() method to detect and set the accelerator */
2738 aToolButton->setText (aTextLabel);
2739 QKeySequence accel = aToolButton->shortcut();
2740 aToolButton->setText (aTextLabel);
2741 aToolButton->setIcon (iset);
2742 /* set the accel last as setIconSet() would kill it */
2743 aToolButton->setShortcut (accel);
2744}
2745
2746/**
2747 * Performs direct and flipped search of position for \a aRectangle to make sure
2748 * it is fully contained inside \a aBoundRegion region by moving & resizing
2749 * \a aRectangle if necessary. Selects the minimum shifted result between direct
2750 * and flipped variants.
2751 */
2752/* static */
2753QRect VBoxGlobal::normalizeGeometry (const QRect &aRectangle, const QRegion &aBoundRegion,
2754 bool aCanResize /* = true */)
2755{
2756 /* Direct search for normalized rectangle */
2757 QRect var1 (getNormalized (aRectangle, aBoundRegion, aCanResize));
2758
2759 /* Flipped search for normalized rectangle */
2760 QRect var2 (flip (getNormalized (flip (aRectangle).boundingRect(),
2761 flip (aBoundRegion), aCanResize)).boundingRect());
2762
2763 /* Calculate shift from starting position for both variants */
2764 double length1 = sqrt (pow ((double) (var1.x() - aRectangle.x()), (double) 2) +
2765 pow ((double) (var1.y() - aRectangle.y()), (double) 2));
2766 double length2 = sqrt (pow ((double) (var2.x() - aRectangle.x()), (double) 2) +
2767 pow ((double) (var2.y() - aRectangle.y()), (double) 2));
2768
2769 /* Return minimum shifted variant */
2770 return length1 > length2 ? var2 : var1;
2771}
2772
2773/**
2774 * Ensures that the given rectangle \a aRectangle is fully contained within the
2775 * region \a aBoundRegion by moving \a aRectangle if necessary. If \a aRectangle is
2776 * larger than \a aBoundRegion, top left corner of \a aRectangle is aligned with the
2777 * top left corner of maximum available rectangle and, if \a aCanResize is true,
2778 * \a aRectangle is shrinked to become fully visible.
2779 */
2780/* static */
2781QRect VBoxGlobal::getNormalized (const QRect &aRectangle, const QRegion &aBoundRegion,
2782 bool /* aCanResize = true */)
2783{
2784 /* Storing available horizontal sub-rectangles & vertical shifts */
2785 int windowVertical = aRectangle.center().y();
2786 QVector <QRect> rectanglesVector (aBoundRegion.rects());
2787 QList <QRect> rectanglesList;
2788 QList <int> shiftsList;
2789 foreach (QRect currentItem, rectanglesVector)
2790 {
2791 int currentDelta = qAbs (windowVertical - currentItem.center().y());
2792 int shift2Top = currentItem.top() - aRectangle.top();
2793 int shift2Bot = currentItem.bottom() - aRectangle.bottom();
2794
2795 int itemPosition = 0;
2796 foreach (QRect item, rectanglesList)
2797 {
2798 int delta = qAbs (windowVertical - item.center().y());
2799 if (delta > currentDelta) break; else ++ itemPosition;
2800 }
2801 rectanglesList.insert (itemPosition, currentItem);
2802
2803 int shift2TopPos = 0;
2804 foreach (int shift, shiftsList)
2805 if (qAbs (shift) > qAbs (shift2Top)) break; else ++ shift2TopPos;
2806 shiftsList.insert (shift2TopPos, shift2Top);
2807
2808 int shift2BotPos = 0;
2809 foreach (int shift, shiftsList)
2810 if (qAbs (shift) > qAbs (shift2Bot)) break; else ++ shift2BotPos;
2811 shiftsList.insert (shift2BotPos, shift2Bot);
2812 }
2813
2814 /* Trying to find the appropriate place for window */
2815 QRect result;
2816 for (int i = -1; i < shiftsList.size(); ++ i)
2817 {
2818 /* Move to appropriate vertical */
2819 QRect rectangle (aRectangle);
2820 if (i >= 0) rectangle.translate (0, shiftsList [i]);
2821
2822 /* Search horizontal shift */
2823 int maxShift = 0;
2824 foreach (QRect item, rectanglesList)
2825 {
2826 QRect trectangle (rectangle.translated (item.left() - rectangle.left(), 0));
2827 if (!item.intersects (trectangle))
2828 continue;
2829
2830 if (rectangle.left() < item.left())
2831 {
2832 int shift = item.left() - rectangle.left();
2833 maxShift = qAbs (shift) > qAbs (maxShift) ? shift : maxShift;
2834 }
2835 else if (rectangle.right() > item.right())
2836 {
2837 int shift = item.right() - rectangle.right();
2838 maxShift = qAbs (shift) > qAbs (maxShift) ? shift : maxShift;
2839 }
2840 }
2841
2842 /* Shift across the horizontal direction */
2843 rectangle.translate (maxShift, 0);
2844
2845 /* Check the translated rectangle to feat the rules */
2846 if (aBoundRegion.united (rectangle) == aBoundRegion)
2847 result = rectangle;
2848
2849 if (!result.isNull()) break;
2850 }
2851
2852 if (result.isNull())
2853 {
2854 /* Resize window to feat desirable size
2855 * using max of available rectangles */
2856 QRect maxRectangle;
2857 quint64 maxSquare = 0;
2858 foreach (QRect item, rectanglesList)
2859 {
2860 quint64 square = item.width() * item.height();
2861 if (square > maxSquare)
2862 {
2863 maxSquare = square;
2864 maxRectangle = item;
2865 }
2866 }
2867
2868 result = aRectangle;
2869 result.moveTo (maxRectangle.x(), maxRectangle.y());
2870 if (maxRectangle.right() < result.right())
2871 result.setRight (maxRectangle.right());
2872 if (maxRectangle.bottom() < result.bottom())
2873 result.setBottom (maxRectangle.bottom());
2874 }
2875
2876 return result;
2877}
2878
2879/**
2880 * Returns the flipped (transposed) region.
2881 */
2882/* static */
2883QRegion VBoxGlobal::flip (const QRegion &aRegion)
2884{
2885 QRegion result;
2886 QVector <QRect> rectangles (aRegion.rects());
2887 foreach (QRect rectangle, rectangles)
2888 result += QRect (rectangle.y(), rectangle.x(),
2889 rectangle.height(), rectangle.width());
2890 return result;
2891}
2892
2893/**
2894 * Aligns the center of \a aWidget with the center of \a aRelative.
2895 *
2896 * If necessary, \a aWidget's position is adjusted to make it fully visible
2897 * within the available desktop area. If \a aWidget is bigger then this area,
2898 * it will also be resized unless \a aCanResize is false or there is an
2899 * inappropriate minimum size limit (in which case the top left corner will be
2900 * simply aligned with the top left corner of the available desktop area).
2901 *
2902 * \a aWidget must be a top-level widget. \a aRelative may be any widget, but
2903 * if it's not top-level itself, its top-level widget will be used for
2904 * calculations. \a aRelative can also be NULL, in which case \a aWidget will
2905 * be centered relative to the available desktop area.
2906 */
2907/* static */
2908void VBoxGlobal::centerWidget (QWidget *aWidget, QWidget *aRelative,
2909 bool aCanResize /* = true */)
2910{
2911 AssertReturnVoid (aWidget);
2912 AssertReturnVoid (aWidget->isTopLevel());
2913
2914 QRect deskGeo, parentGeo;
2915 QWidget *w = aRelative;
2916 if (w)
2917 {
2918 w = w->window();
2919 deskGeo = QApplication::desktop()->availableGeometry (w);
2920 parentGeo = w->frameGeometry();
2921 /* On X11/Gnome, geo/frameGeo.x() and y() are always 0 for top level
2922 * widgets with parents, what a shame. Use mapToGlobal() to workaround. */
2923 QPoint d = w->mapToGlobal (QPoint (0, 0));
2924 d.rx() -= w->geometry().x() - w->x();
2925 d.ry() -= w->geometry().y() - w->y();
2926 parentGeo.moveTopLeft (d);
2927 }
2928 else
2929 {
2930 deskGeo = QApplication::desktop()->availableGeometry();
2931 parentGeo = deskGeo;
2932 }
2933
2934 /* On X11, there is no way to determine frame geometry (including WM
2935 * decorations) before the widget is shown for the first time. Stupidly
2936 * enumerate other top level widgets to find the thickest frame. The code
2937 * is based on the idea taken from QDialog::adjustPositionInternal(). */
2938
2939 int extraw = 0, extrah = 0;
2940
2941 QWidgetList list = QApplication::topLevelWidgets();
2942 QListIterator<QWidget*> it (list);
2943 while ((extraw == 0 || extrah == 0) && it.hasNext())
2944 {
2945 int framew, frameh;
2946 QWidget *current = it.next();
2947 if (!current->isVisible())
2948 continue;
2949
2950 framew = current->frameGeometry().width() - current->width();
2951 frameh = current->frameGeometry().height() - current->height();
2952
2953 extraw = qMax (extraw, framew);
2954 extrah = qMax (extrah, frameh);
2955 }
2956
2957 /// @todo (r=dmik) not sure if we really need this
2958#if 0
2959 /* sanity check for decoration frames. With embedding, we
2960 * might get extraordinary values */
2961 if (extraw == 0 || extrah == 0 || extraw > 20 || extrah > 50)
2962 {
2963 extrah = 50;
2964 extraw = 20;
2965 }
2966#endif
2967
2968 /* On non-X11 platforms, the following would be enough instead of the
2969 * above workaround: */
2970 // QRect geo = frameGeometry();
2971 QRect geo = QRect (0, 0, aWidget->width() + extraw,
2972 aWidget->height() + extrah);
2973
2974 geo.moveCenter (QPoint (parentGeo.x() + (parentGeo.width() - 1) / 2,
2975 parentGeo.y() + (parentGeo.height() - 1) / 2));
2976
2977 /* ensure the widget is within the available desktop area */
2978 QRect newGeo = normalizeGeometry (geo, deskGeo, aCanResize);
2979#ifdef Q_WS_MAC
2980 /* No idea why, but Qt doesn't respect if there is a unified toolbar on the
2981 * ::move call. So manually add the height of the toolbar before setting
2982 * the position. */
2983 if (w)
2984 newGeo.translate (0, ::darwinWindowToolBarHeight (aWidget));
2985#endif /* Q_WS_MAC */
2986
2987 aWidget->move (newGeo.topLeft());
2988
2989 if (aCanResize &&
2990 (geo.width() != newGeo.width() || geo.height() != newGeo.height()))
2991 aWidget->resize (newGeo.width() - extraw, newGeo.height() - extrah);
2992}
2993
2994/**
2995 * Returns the decimal separator for the current locale.
2996 */
2997/* static */
2998QChar VBoxGlobal::decimalSep()
2999{
3000 return QLocale::system().decimalPoint();
3001}
3002
3003/**
3004 * Returns the regexp string that defines the format of the human-readable
3005 * size representation, <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
3006 *
3007 * This regexp will capture 5 groups of text:
3008 * - cap(1): integer number in case when no decimal point is present
3009 * (if empty, it means that decimal point is present)
3010 * - cap(2): size suffix in case when no decimal point is present (may be empty)
3011 * - cap(3): integer number in case when decimal point is present (may be empty)
3012 * - cap(4): fraction number (hundredth) in case when decimal point is present
3013 * - cap(5): size suffix in case when decimal point is present (note that
3014 * B cannot appear there)
3015 */
3016/* static */
3017QString VBoxGlobal::sizeRegexp()
3018{
3019 QString regexp =
3020 QString ("^(?:(?:(\\d+)(?:\\s?(%2|%3|%4|%5|%6|%7))?)|(?:(\\d*)%1(\\d{1,2})(?:\\s?(%3|%4|%5|%6|%7))))$")
3021 .arg (decimalSep())
3022 .arg (tr ("B", "size suffix Bytes"))
3023 .arg (tr ("KB", "size suffix KBytes=1024 Bytes"))
3024 .arg (tr ("MB", "size suffix MBytes=1024 KBytes"))
3025 .arg (tr ("GB", "size suffix GBytes=1024 MBytes"))
3026 .arg (tr ("TB", "size suffix TBytes=1024 GBytes"))
3027 .arg (tr ("PB", "size suffix PBytes=1024 TBytes"));
3028 return regexp;
3029}
3030
3031/* static */
3032QString VBoxGlobal::toHumanReadableList(const QStringList &list)
3033{
3034 QString strList;
3035 for (int i = 0; i < list.size(); ++i)
3036 {
3037 strList += list.at(i);
3038 if (i < list.size() - 1)
3039 strList += + " ";
3040 }
3041 return strList;
3042}
3043
3044/**
3045 * Parses the given size string that should be in form of
3046 * <tt>####[.##] B|KB|MB|GB|TB|PB</tt> and returns
3047 * the size value in bytes. Zero is returned on error.
3048 */
3049/* static */
3050quint64 VBoxGlobal::parseSize (const QString &aText)
3051{
3052 QRegExp regexp (sizeRegexp());
3053 int pos = regexp.indexIn (aText);
3054 if (pos != -1)
3055 {
3056 QString intgS = regexp.cap (1);
3057 QString hundS;
3058 QString suff = regexp.cap (2);
3059 if (intgS.isEmpty())
3060 {
3061 intgS = regexp.cap (3);
3062 hundS = regexp.cap (4);
3063 suff = regexp.cap (5);
3064 }
3065
3066 quint64 denom = 0;
3067 if (suff.isEmpty() || suff == tr ("B", "size suffix Bytes"))
3068 denom = 1;
3069 else if (suff == tr ("KB", "size suffix KBytes=1024 Bytes"))
3070 denom = _1K;
3071 else if (suff == tr ("MB", "size suffix MBytes=1024 KBytes"))
3072 denom = _1M;
3073 else if (suff == tr ("GB", "size suffix GBytes=1024 MBytes"))
3074 denom = _1G;
3075 else if (suff == tr ("TB", "size suffix TBytes=1024 GBytes"))
3076 denom = _1T;
3077 else if (suff == tr ("PB", "size suffix PBytes=1024 TBytes"))
3078 denom = _1P;
3079
3080 quint64 intg = intgS.toULongLong();
3081 if (denom == 1)
3082 return intg;
3083
3084 quint64 hund = hundS.leftJustified (2, '0').toULongLong();
3085 hund = hund * denom / 100;
3086 intg = intg * denom + hund;
3087 return intg;
3088 }
3089 else
3090 return 0;
3091}
3092
3093/**
3094 * Formats the given @a aSize value in bytes to a human readable string
3095 * in form of <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
3096 *
3097 * The @a aMode and @a aDecimal parameters are used for rounding the resulting
3098 * number when converting the size value to KB, MB, etc gives a fractional part:
3099 * <ul>
3100 * <li>When \a aMode is FormatSize_Round, the result is rounded to the
3101 * closest number containing \a aDecimal decimal digits.
3102 * </li>
3103 * <li>When \a aMode is FormatSize_RoundDown, the result is rounded to the
3104 * largest number with \a aDecimal decimal digits that is not greater than
3105 * the result. This guarantees that converting the resulting string back to
3106 * the integer value in bytes will not produce a value greater that the
3107 * initial size parameter.
3108 * </li>
3109 * <li>When \a aMode is FormatSize_RoundUp, the result is rounded to the
3110 * smallest number with \a aDecimal decimal digits that is not less than the
3111 * result. This guarantees that converting the resulting string back to the
3112 * integer value in bytes will not produce a value less that the initial
3113 * size parameter.
3114 * </li>
3115 * </ul>
3116 *
3117 * @param aSize Size value in bytes.
3118 * @param aMode Conversion mode.
3119 * @param aDecimal Number of decimal digits in result.
3120 * @return Human-readable size string.
3121 */
3122/* static */
3123QString VBoxGlobal::formatSize (quint64 aSize, uint aDecimal /* = 2 */,
3124 FormatSize aMode /* = FormatSize_Round */)
3125{
3126 static QString Suffixes [7];
3127 Suffixes[0] = tr ("B", "size suffix Bytes");
3128 Suffixes[1] = tr ("KB", "size suffix KBytes=1024 Bytes");
3129 Suffixes[2] = tr ("MB", "size suffix MBytes=1024 KBytes");
3130 Suffixes[3] = tr ("GB", "size suffix GBytes=1024 MBytes");
3131 Suffixes[4] = tr ("TB", "size suffix TBytes=1024 GBytes");
3132 Suffixes[5] = tr ("PB", "size suffix PBytes=1024 TBytes");
3133 Suffixes[6] = (const char *)NULL;
3134 AssertCompile(6 < RT_ELEMENTS (Suffixes));
3135
3136 quint64 denom = 0;
3137 int suffix = 0;
3138
3139 if (aSize < _1K)
3140 {
3141 denom = 1;
3142 suffix = 0;
3143 }
3144 else if (aSize < _1M)
3145 {
3146 denom = _1K;
3147 suffix = 1;
3148 }
3149 else if (aSize < _1G)
3150 {
3151 denom = _1M;
3152 suffix = 2;
3153 }
3154 else if (aSize < _1T)
3155 {
3156 denom = _1G;
3157 suffix = 3;
3158 }
3159 else if (aSize < _1P)
3160 {
3161 denom = _1T;
3162 suffix = 4;
3163 }
3164 else
3165 {
3166 denom = _1P;
3167 suffix = 5;
3168 }
3169
3170 quint64 intg = aSize / denom;
3171 quint64 decm = aSize % denom;
3172 quint64 mult = 1;
3173 for (uint i = 0; i < aDecimal; ++ i) mult *= 10;
3174
3175 QString number;
3176 if (denom > 1)
3177 {
3178 if (decm)
3179 {
3180 decm *= mult;
3181 /* not greater */
3182 if (aMode == FormatSize_RoundDown)
3183 decm = decm / denom;
3184 /* not less */
3185 else if (aMode == FormatSize_RoundUp)
3186 decm = (decm + denom - 1) / denom;
3187 /* nearest */
3188 else decm = (decm + denom / 2) / denom;
3189 }
3190 /* check for the fractional part overflow due to rounding */
3191 if (decm == mult)
3192 {
3193 decm = 0;
3194 ++ intg;
3195 /* check if we've got 1024 XB after rounding and scale down if so */
3196 if (intg == 1024 && Suffixes [suffix + 1] != NULL)
3197 {
3198 intg /= 1024;
3199 ++ suffix;
3200 }
3201 }
3202 number = QString::number (intg);
3203 if (aDecimal) number += QString ("%1%2").arg (decimalSep())
3204 .arg (QString::number (decm).rightJustified (aDecimal, '0'));
3205 }
3206 else
3207 {
3208 number = QString::number (intg);
3209 }
3210
3211 return QString ("%1 %2").arg (number).arg (Suffixes [suffix]);
3212}
3213
3214/**
3215 * Returns the required video memory in bytes for the current desktop
3216 * resolution at maximum possible screen depth in bpp.
3217 */
3218/* static */
3219quint64 VBoxGlobal::requiredVideoMemory(const QString &strGuestOSTypeId, int cMonitors /* = 1 */)
3220{
3221 QDesktopWidget *pDW = QApplication::desktop();
3222 /* We create a list of the size of all available host monitors. This list
3223 * is sorted by value and by starting with the biggest one, we calculate
3224 * the memory requirements for every guest screen. This is of course not
3225 * correct, but as we can't predict on which host screens the user will
3226 * open the guest windows, this is the best assumption we can do, cause it
3227 * is the worst case. */
3228 QVector<int> screenSize(qMax(cMonitors, pDW->numScreens()), 0);
3229 for (int i = 0; i < pDW->numScreens(); ++i)
3230 {
3231 QRect r = pDW->screenGeometry(i);
3232 screenSize[i] = r.width() * r.height();
3233 }
3234 /* Now sort the vector */
3235 qSort(screenSize.begin(), screenSize.end(), qGreater<int>());
3236 /* For the case that there are more guest screens configured then host
3237 * screens available, replace all zeros with the greatest value in the
3238 * vector. */
3239 for (int i = 0; i < screenSize.size(); ++i)
3240 if (screenSize.at(i) == 0)
3241 screenSize.replace(i, screenSize.at(0));
3242
3243 quint64 needBits = 0;
3244 for (int i = 0; i < cMonitors; ++i)
3245 {
3246 /* Calculate summary required memory amount in bits */
3247 needBits += (screenSize.at(i) * /* with x height */
3248 32 + /* we will take the maximum possible bpp for now */
3249 8 * _1M) + /* current cache per screen - may be changed in future */
3250 8 * 4096; /* adapter info */
3251 }
3252 /* Translate value into megabytes with rounding to highest side */
3253 quint64 needMBytes = needBits % (8 * _1M) ? needBits / (8 * _1M) + 1 :
3254 needBits / (8 * _1M) /* convert to megabytes */;
3255
3256 if (strGuestOSTypeId.startsWith("Windows"))
3257 {
3258 /* Windows guests need offscreen VRAM too for graphics acceleration features: */
3259#ifdef VBOX_WITH_CRHGSMI
3260 if (isWddmCompatibleOsType(strGuestOSTypeId))
3261 {
3262 /* wddm mode, there are two surfaces for each screen: shadow & primary */
3263 needMBytes *= 3;
3264 }
3265 else
3266#endif /* VBOX_WITH_CRHGSMI */
3267 {
3268 needMBytes *= 2;
3269 }
3270 }
3271
3272 return needMBytes * _1M;
3273}
3274
3275/**
3276 * Puts soft hyphens after every path component in the given file name.
3277 *
3278 * @param aFileName File name (must be a full path name).
3279 */
3280/* static */
3281QString VBoxGlobal::locationForHTML (const QString &aFileName)
3282{
3283/// @todo (dmik) remove?
3284// QString result = QDir::toNativeSeparators (fn);
3285//#ifdef Q_OS_LINUX
3286// result.replace ('/', "/<font color=red>&shy;</font>");
3287//#else
3288// result.replace ('\\', "\\<font color=red>&shy;</font>");
3289//#endif
3290// return result;
3291 QFileInfo fi (aFileName);
3292 return fi.fileName();
3293}
3294
3295/**
3296 * Reformats the input string @a aStr so that:
3297 * - strings in single quotes will be put inside <nobr> and marked
3298 * with blue color;
3299 * - UUIDs be put inside <nobr> and marked
3300 * with green color;
3301 * - replaces new line chars with </p><p> constructs to form paragraphs
3302 * (note that <p> and </p> are not appended to the beginning and to the
3303 * end of the string respectively, to allow the result be appended
3304 * or prepended to the existing paragraph).
3305 *
3306 * If @a aToolTip is true, colouring is not applied, only the <nobr> tag
3307 * is added. Also, new line chars are replaced with <br> instead of <p>.
3308 */
3309/* static */
3310QString VBoxGlobal::highlight (const QString &aStr, bool aToolTip /* = false */)
3311{
3312 QString strFont;
3313 QString uuidFont;
3314 QString endFont;
3315 if (!aToolTip)
3316 {
3317 strFont = "<font color=#0000CC>";
3318 uuidFont = "<font color=#008000>";
3319 endFont = "</font>";
3320 }
3321
3322 QString text = aStr;
3323
3324 /* replace special entities, '&' -- first! */
3325 text.replace ('&', "&amp;");
3326 text.replace ('<', "&lt;");
3327 text.replace ('>', "&gt;");
3328 text.replace ('\"', "&quot;");
3329
3330 /* mark strings in single quotes with color */
3331 QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
3332 rx.setMinimal (true);
3333 text.replace (rx,
3334 QString ("\\1%1<nobr>'\\2'</nobr>%2").arg (strFont).arg (endFont));
3335
3336 /* mark UUIDs with color */
3337 text.replace (QRegExp (
3338 "((?:^|\\s)[(]?)"
3339 "(\\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\})"
3340 "(?=[:.-!);]?(?:\\s|$))"),
3341 QString ("\\1%1<nobr>\\2</nobr>%2").arg (uuidFont).arg (endFont));
3342
3343 /* split to paragraphs at \n chars */
3344 if (!aToolTip)
3345 text.replace ('\n', "</p><p>");
3346 else
3347 text.replace ('\n', "<br>");
3348
3349 return text;
3350}
3351
3352/* static */
3353QString VBoxGlobal::replaceHtmlEntities(QString strText)
3354{
3355 return strText
3356 .replace('&', "&amp;")
3357 .replace('<', "&lt;")
3358 .replace('>', "&gt;")
3359 .replace('\"', "&quot;");
3360}
3361
3362/**
3363 * Reformats the input string @a aStr so that:
3364 * - strings in single quotes will be put inside <nobr> and marked
3365 * with bold style;
3366 * - UUIDs be put inside <nobr> and marked
3367 * with italic style;
3368 * - replaces new line chars with </p><p> constructs to form paragraphs
3369 * (note that <p> and </p> are not appended to the beginning and to the
3370 * end of the string respectively, to allow the result be appended
3371 * or prepended to the existing paragraph).
3372 */
3373/* static */
3374QString VBoxGlobal::emphasize (const QString &aStr)
3375{
3376 QString strEmphStart ("<b>");
3377 QString strEmphEnd ("</b>");
3378 QString uuidEmphStart ("<i>");
3379 QString uuidEmphEnd ("</i>");
3380
3381 QString text = aStr;
3382
3383 /* replace special entities, '&' -- first! */
3384 text.replace ('&', "&amp;");
3385 text.replace ('<', "&lt;");
3386 text.replace ('>', "&gt;");
3387 text.replace ('\"', "&quot;");
3388
3389 /* mark strings in single quotes with bold style */
3390 QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
3391 rx.setMinimal (true);
3392 text.replace (rx,
3393 QString ("\\1%1<nobr>'\\2'</nobr>%2").arg (strEmphStart).arg (strEmphEnd));
3394
3395 /* mark UUIDs with italic style */
3396 text.replace (QRegExp (
3397 "((?:^|\\s)[(]?)"
3398 "(\\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\})"
3399 "(?=[:.-!);]?(?:\\s|$))"),
3400 QString ("\\1%1<nobr>\\2</nobr>%2").arg (uuidEmphStart).arg (uuidEmphEnd));
3401
3402 /* split to paragraphs at \n chars */
3403 text.replace ('\n', "</p><p>");
3404
3405 return text;
3406}
3407
3408/**
3409 * This does exactly the same as QLocale::system().name() but corrects its
3410 * wrong behavior on Linux systems (LC_NUMERIC for some strange reason takes
3411 * precedence over any other locale setting in the QLocale::system()
3412 * implementation). This implementation first looks at LC_ALL (as defined by
3413 * SUS), then looks at LC_MESSAGES which is designed to define a language for
3414 * program messages in case if it differs from the language for other locale
3415 * categories. Then it looks for LANG and finally falls back to
3416 * QLocale::system().name().
3417 *
3418 * The order of precedence is well defined here:
3419 * http://opengroup.org/onlinepubs/007908799/xbd/envvar.html
3420 *
3421 * @note This method will return "C" when the requested locale is invalid or
3422 * when the "C" locale is set explicitly.
3423 */
3424/* static */
3425QString VBoxGlobal::systemLanguageId()
3426{
3427#if defined (Q_WS_MAC)
3428 /* QLocale return the right id only if the user select the format of the
3429 * language also. So we use our own implementation */
3430 return ::darwinSystemLanguage();
3431#elif defined (Q_OS_UNIX)
3432 const char *s = RTEnvGet ("LC_ALL");
3433 if (s == 0)
3434 s = RTEnvGet ("LC_MESSAGES");
3435 if (s == 0)
3436 s = RTEnvGet ("LANG");
3437 if (s != 0)
3438 return QLocale (s).name();
3439#endif
3440 return QLocale::system().name();
3441}
3442
3443#if defined (Q_WS_X11)
3444
3445static char *XXGetProperty (Display *aDpy, Window aWnd,
3446 Atom aPropType, const char *aPropName)
3447{
3448 Atom propNameAtom = XInternAtom (aDpy, aPropName,
3449 True /* only_if_exists */);
3450 if (propNameAtom == None)
3451 return NULL;
3452
3453 Atom actTypeAtom = None;
3454 int actFmt = 0;
3455 unsigned long nItems = 0;
3456 unsigned long nBytesAfter = 0;
3457 unsigned char *propVal = NULL;
3458 int rc = XGetWindowProperty (aDpy, aWnd, propNameAtom,
3459 0, LONG_MAX, False /* delete */,
3460 aPropType, &actTypeAtom, &actFmt,
3461 &nItems, &nBytesAfter, &propVal);
3462 if (rc != Success)
3463 return NULL;
3464
3465 return reinterpret_cast <char *> (propVal);
3466}
3467
3468static Bool XXSendClientMessage (Display *aDpy, Window aWnd, const char *aMsg,
3469 unsigned long aData0 = 0, unsigned long aData1 = 0,
3470 unsigned long aData2 = 0, unsigned long aData3 = 0,
3471 unsigned long aData4 = 0)
3472{
3473 Atom msgAtom = XInternAtom (aDpy, aMsg, True /* only_if_exists */);
3474 if (msgAtom == None)
3475 return False;
3476
3477 XEvent ev;
3478
3479 ev.xclient.type = ClientMessage;
3480 ev.xclient.serial = 0;
3481 ev.xclient.send_event = True;
3482 ev.xclient.display = aDpy;
3483 ev.xclient.window = aWnd;
3484 ev.xclient.message_type = msgAtom;
3485
3486 /* always send as 32 bit for now */
3487 ev.xclient.format = 32;
3488 ev.xclient.data.l [0] = aData0;
3489 ev.xclient.data.l [1] = aData1;
3490 ev.xclient.data.l [2] = aData2;
3491 ev.xclient.data.l [3] = aData3;
3492 ev.xclient.data.l [4] = aData4;
3493
3494 return XSendEvent (aDpy, DefaultRootWindow (aDpy), False,
3495 SubstructureRedirectMask, &ev) != 0;
3496}
3497
3498#endif
3499
3500/**
3501 * Activates the specified window. If necessary, the window will be
3502 * de-iconified activation.
3503 *
3504 * @note On X11, it is implied that @a aWid represents a window of the same
3505 * display the application was started on.
3506 *
3507 * @param aWId Window ID to activate.
3508 * @param aSwitchDesktop @c true to switch to the window's desktop before
3509 * activation.
3510 *
3511 * @return @c true on success and @c false otherwise.
3512 */
3513/* static */
3514bool VBoxGlobal::activateWindow (WId aWId, bool aSwitchDesktop /* = true */)
3515{
3516 bool result = true;
3517
3518#if defined (Q_WS_WIN32)
3519
3520 if (IsIconic (aWId))
3521 result &= !!ShowWindow (aWId, SW_RESTORE);
3522 else if (!IsWindowVisible (aWId))
3523 result &= !!ShowWindow (aWId, SW_SHOW);
3524
3525 result &= !!SetForegroundWindow (aWId);
3526
3527#elif defined (Q_WS_X11)
3528
3529 Display *dpy = QX11Info::display();
3530
3531 if (aSwitchDesktop)
3532 {
3533 /* try to find the desktop ID using the NetWM property */
3534 CARD32 *desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
3535 "_NET_WM_DESKTOP");
3536 if (desktop == NULL)
3537 /* if the NetWM properly is not supported try to find the desktop
3538 * ID using the GNOME WM property */
3539 desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
3540 "_WIN_WORKSPACE");
3541
3542 if (desktop != NULL)
3543 {
3544 Bool ok = XXSendClientMessage (dpy, DefaultRootWindow (dpy),
3545 "_NET_CURRENT_DESKTOP",
3546 *desktop);
3547 if (!ok)
3548 {
3549 LogWarningFunc (("Couldn't switch to desktop=%08X\n",
3550 desktop));
3551 result = false;
3552 }
3553 XFree (desktop);
3554 }
3555 else
3556 {
3557 LogWarningFunc (("Couldn't find a desktop ID for aWId=%08X\n",
3558 aWId));
3559 result = false;
3560 }
3561 }
3562
3563 Bool ok = XXSendClientMessage (dpy, aWId, "_NET_ACTIVE_WINDOW");
3564 result &= !!ok;
3565
3566 XRaiseWindow (dpy, aWId);
3567
3568#else
3569
3570 NOREF (aWId);
3571 NOREF (aSwitchDesktop);
3572 AssertFailed();
3573 result = false;
3574
3575#endif
3576
3577 if (!result)
3578 LogWarningFunc (("Couldn't activate aWId=%08X\n", aWId));
3579
3580 return result;
3581}
3582
3583/**
3584 * Removes the accelerator mark (the ampersand symbol) from the given string
3585 * and returns the result. The string is supposed to be a menu item's text
3586 * that may (or may not) contain the accelerator mark.
3587 *
3588 * In order to support accelerators used in non-alphabet languages
3589 * (e.g. Japanese) that has a form of "(&<L>)" (where <L> is a latin letter),
3590 * this method first searches for this pattern and, if found, removes it as a
3591 * whole. If such a pattern is not found, then the '&' character is simply
3592 * removed from the string.
3593 *
3594 * @note This function removes only the first occurrence of the accelerator
3595 * mark.
3596 *
3597 * @param aText Menu item's text to remove the accelerator mark from.
3598 *
3599 * @return The resulting string.
3600 */
3601/* static */
3602QString VBoxGlobal::removeAccelMark (const QString &aText)
3603{
3604 QString result = aText;
3605
3606 QRegExp accel ("\\(&[a-zA-Z]\\)");
3607 int pos = accel.indexIn (result);
3608 if (pos >= 0)
3609 result.remove (pos, accel.cap().length());
3610 else
3611 {
3612 pos = result.indexOf ('&');
3613 if (pos >= 0)
3614 result.remove (pos, 1);
3615 }
3616
3617 return result;
3618}
3619
3620/* static */
3621QString VBoxGlobal::insertKeyToActionText(const QString &strText, const QString &strKey)
3622{
3623#ifdef Q_WS_MAC
3624 QString pattern("%1 (Host+%2)");
3625#else
3626 QString pattern("%1 \tHost+%2");
3627#endif
3628 if ( strKey.isEmpty()
3629 || strKey.compare("None", Qt::CaseInsensitive) == 0)
3630 return strText;
3631 else
3632 return pattern.arg(strText).arg(QKeySequence(strKey).toString(QKeySequence::NativeText));
3633}
3634
3635/* static */
3636QString VBoxGlobal::extractKeyFromActionText (const QString &aText)
3637{
3638 QString key;
3639#ifdef Q_WS_MAC
3640 QRegExp re (".* \\(Host\\+(.+)\\)");
3641#else
3642 QRegExp re (".* \\t\\Host\\+(.+)");
3643#endif
3644 if (re.exactMatch (aText))
3645 key = re.cap (1);
3646 return key;
3647}
3648
3649/**
3650 * Joins two pixmaps horizontally with 2px space between them and returns the
3651 * result.
3652 *
3653 * @param aPM1 Left pixmap.
3654 * @param aPM2 Right pixmap.
3655 */
3656/* static */
3657QPixmap VBoxGlobal::joinPixmaps (const QPixmap &aPM1, const QPixmap &aPM2)
3658{
3659 if (aPM1.isNull())
3660 return aPM2;
3661 if (aPM2.isNull())
3662 return aPM1;
3663
3664 QPixmap result (aPM1.width() + aPM2.width() + 2,
3665 qMax (aPM1.height(), aPM2.height()));
3666 result.fill (Qt::transparent);
3667
3668 QPainter painter (&result);
3669 painter.drawPixmap (0, 0, aPM1);
3670 painter.drawPixmap (aPM1.width() + 2, result.height() - aPM2.height(), aPM2);
3671 painter.end();
3672
3673 return result;
3674}
3675
3676/**
3677 * Searches for a widget that with @a aName (if it is not NULL) which inherits
3678 * @a aClassName (if it is not NULL) and among children of @a aParent. If @a
3679 * aParent is NULL, all top-level widgets are searched. If @a aRecursive is
3680 * true, child widgets are recursively searched as well.
3681 */
3682/* static */
3683QWidget *VBoxGlobal::findWidget (QWidget *aParent, const char *aName,
3684 const char *aClassName /* = NULL */,
3685 bool aRecursive /* = false */)
3686{
3687 if (aParent == NULL)
3688 {
3689 QWidgetList list = QApplication::topLevelWidgets();
3690 foreach(QWidget *w, list)
3691 {
3692 if ((!aName || strcmp (w->objectName().toAscii().constData(), aName) == 0) &&
3693 (!aClassName || strcmp (w->metaObject()->className(), aClassName) == 0))
3694 return w;
3695 if (aRecursive)
3696 {
3697 w = findWidget (w, aName, aClassName, aRecursive);
3698 if (w)
3699 return w;
3700 }
3701 }
3702 return NULL;
3703 }
3704
3705 /* Find the first children of aParent with the appropriate properties.
3706 * Please note that this call is recursively. */
3707 QList<QWidget *> list = qFindChildren<QWidget *> (aParent, aName);
3708 foreach(QWidget *child, list)
3709 {
3710 if (!aClassName || strcmp (child->metaObject()->className(), aClassName) == 0)
3711 return child;
3712 }
3713 return NULL;
3714}
3715
3716/**
3717 * Figures out which medium formats are currently supported by VirtualBox for
3718 * the given device type.
3719 * Returned is a list of pairs with the form
3720 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3721 */
3722/* static */
3723QList <QPair <QString, QString> > VBoxGlobal::MediumBackends(KDeviceType enmType)
3724{
3725 CSystemProperties systemProperties = vboxGlobal().virtualBox().GetSystemProperties();
3726 QVector<CMediumFormat> mediumFormats = systemProperties.GetMediumFormats();
3727 QList< QPair<QString, QString> > backendPropList;
3728 for (int i = 0; i < mediumFormats.size(); ++ i)
3729 {
3730 /* File extensions */
3731 QVector <QString> fileExtensions;
3732 QVector <KDeviceType> deviceTypes;
3733
3734 mediumFormats [i].DescribeFileExtensions(fileExtensions, deviceTypes);
3735
3736 QStringList f;
3737 for (int a = 0; a < fileExtensions.size(); ++ a)
3738 if (deviceTypes [a] == enmType)
3739 f << QString ("*.%1").arg (fileExtensions [a]);
3740 /* Create a pair out of the backend description and all suffix's. */
3741 if (!f.isEmpty())
3742 backendPropList << QPair<QString, QString> (mediumFormats [i].GetName(), f.join(" "));
3743 }
3744 return backendPropList;
3745}
3746
3747/**
3748 * Figures out which hard disk formats are currently supported by VirtualBox.
3749 * Returned is a list of pairs with the form
3750 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3751 */
3752/* static */
3753QList <QPair <QString, QString> > VBoxGlobal::HDDBackends()
3754{
3755 return MediumBackends(KDeviceType_HardDisk);
3756}
3757
3758/**
3759 * Figures out which CD/DVD disk formats are currently supported by VirtualBox.
3760 * Returned is a list of pairs with the form
3761 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3762 */
3763/* static */
3764QList <QPair <QString, QString> > VBoxGlobal::DVDBackends()
3765{
3766 return MediumBackends(KDeviceType_DVD);
3767}
3768
3769/**
3770 * Figures out which floppy disk formats are currently supported by VirtualBox.
3771 * Returned is a list of pairs with the form
3772 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3773 */
3774/* static */
3775QList <QPair <QString, QString> > VBoxGlobal::FloppyBackends()
3776{
3777 return MediumBackends(KDeviceType_Floppy);
3778}
3779
3780/* static */
3781QString VBoxGlobal::documentsPath()
3782{
3783 QString path;
3784#if QT_VERSION < 0x040400
3785 path = QDir::homePath();
3786#else
3787 path = QDesktopServices::storageLocation (QDesktopServices::DocumentsLocation);
3788#endif
3789
3790 /* Make sure the path exists */
3791 QDir dir (path);
3792 if (dir.exists())
3793 return QDir::cleanPath (dir.canonicalPath());
3794 else
3795 {
3796 dir.setPath (QDir::homePath() + "/Documents");
3797 if (dir.exists())
3798 return QDir::cleanPath (dir.canonicalPath());
3799 else
3800 return QDir::homePath();
3801 }
3802}
3803
3804#ifdef VBOX_WITH_VIDEOHWACCEL
3805/* static */
3806bool VBoxGlobal::isAcceleration2DVideoAvailable()
3807{
3808 return VBoxQGLOverlay::isAcceleration2DVideoAvailable();
3809}
3810
3811/** additional video memory required for the best 2D support performance
3812 * total amount of VRAM required is thus calculated as requiredVideoMemory + required2DOffscreenVideoMemory */
3813/* static */
3814quint64 VBoxGlobal::required2DOffscreenVideoMemory()
3815{
3816 return VBoxQGLOverlay::required2DOffscreenVideoMemory();
3817}
3818
3819#endif
3820
3821#ifdef VBOX_WITH_CRHGSMI
3822/* static */
3823quint64 VBoxGlobal::required3DWddmOffscreenVideoMemory(const QString &strGuestOSTypeId, int cMonitors /* = 1 */)
3824{
3825 cMonitors = RT_MAX(cMonitors, 1);
3826 quint64 cbSize = VBoxGlobal::requiredVideoMemory(strGuestOSTypeId, 1); /* why not cMonitors? */
3827 cbSize += 64 * _1M;
3828 return cbSize;
3829}
3830
3831/* static */
3832bool VBoxGlobal::isWddmCompatibleOsType(const QString &strGuestOSTypeId)
3833{
3834 return strGuestOSTypeId.startsWith("WindowsVista")
3835 || strGuestOSTypeId.startsWith("Windows7")
3836 || strGuestOSTypeId.startsWith("Windows8")
3837 || strGuestOSTypeId.startsWith("Windows2008");
3838}
3839#endif /* VBOX_WITH_CRHGSMI */
3840
3841#ifdef Q_WS_MAC
3842bool VBoxGlobal::isSheetWindowAllowed(QWidget *pParent) const
3843{
3844 /* Make sure Mac Sheet is not used for the same parent now. */
3845 if (sheetWindowUsed(pParent))
3846 return false;
3847
3848 /* No sheets for fullscreen/seamless now.
3849 * Firstly it looks ugly and secondly in some cases it is broken. */
3850 if (!(qobject_cast<UIMachineWindowFullscreen*>(pParent) ||
3851 qobject_cast<UIMachineWindowSeamless*>(pParent)))
3852 return true;
3853
3854 return false;
3855}
3856
3857void VBoxGlobal::setSheetWindowUsed(QWidget *pParent, bool fUsed)
3858{
3859 if (fUsed)
3860 {
3861 AssertMsg(!m_sheets.contains(pParent), ("Trying to use Mac Sheet for parent which already has one!"));
3862 if (m_sheets.contains(pParent))
3863 return;
3864 }
3865 else
3866 {
3867 AssertMsg(m_sheets.contains(pParent), ("Trying to cancel use Mac Sheet for parent which has no one!"));
3868 if (!m_sheets.contains(pParent))
3869 return;
3870 }
3871
3872 if (fUsed)
3873 m_sheets.insert(pParent);
3874 else
3875 m_sheets.remove(pParent);
3876}
3877
3878bool VBoxGlobal::sheetWindowUsed(QWidget *pParent) const
3879{
3880 return m_sheets.contains(pParent);
3881}
3882#endif /* Q_WS_MAC */
3883
3884/* static */
3885QString VBoxGlobal::fullMediumFormatName(const QString &strBaseMediumFormatName)
3886{
3887 if (strBaseMediumFormatName == "VDI")
3888 return tr("VDI (VirtualBox Disk Image)");
3889 else if (strBaseMediumFormatName == "VMDK")
3890 return tr("VMDK (Virtual Machine Disk)");
3891 else if (strBaseMediumFormatName == "VHD")
3892 return tr("VHD (Virtual Hard Disk)");
3893 else if (strBaseMediumFormatName == "Parallels")
3894 return tr("HDD (Parallels Hard Disk)");
3895 else if (strBaseMediumFormatName == "QED")
3896 return tr("QED (QEMU enhanced disk)");
3897 else if (strBaseMediumFormatName == "QCOW")
3898 return tr("QCOW (QEMU Copy-On-Write)");
3899 return strBaseMediumFormatName;
3900}
3901
3902// Public slots
3903////////////////////////////////////////////////////////////////////////////////
3904
3905/**
3906 * Opens the specified URL using OS/Desktop capabilities.
3907 *
3908 * @param aURL URL to open
3909 *
3910 * @return true on success and false otherwise
3911 */
3912bool VBoxGlobal::openURL (const QString &aURL)
3913{
3914 /* Service event */
3915 class ServiceEvent : public QEvent
3916 {
3917 public:
3918
3919 ServiceEvent (bool aResult) : QEvent (QEvent::User), mResult (aResult) {}
3920
3921 bool result() const { return mResult; }
3922
3923 private:
3924
3925 bool mResult;
3926 };
3927
3928 /* Service-Client object */
3929 class ServiceClient : public QEventLoop
3930 {
3931 public:
3932
3933 ServiceClient() : mResult (false) {}
3934
3935 bool result() const { return mResult; }
3936
3937 private:
3938
3939 bool event (QEvent *aEvent)
3940 {
3941 if (aEvent->type() == QEvent::User)
3942 {
3943 ServiceEvent *pEvent = static_cast <ServiceEvent*> (aEvent);
3944 mResult = pEvent->result();
3945 pEvent->accept();
3946 quit();
3947 return true;
3948 }
3949 return false;
3950 }
3951
3952 bool mResult;
3953 };
3954
3955 /* Service-Server object */
3956 class ServiceServer : public QThread
3957 {
3958 public:
3959
3960 ServiceServer (ServiceClient &aClient, const QString &sURL)
3961 : mClient (aClient), mURL (sURL) {}
3962
3963 private:
3964
3965 void run()
3966 {
3967 QApplication::postEvent (&mClient, new ServiceEvent (QDesktopServices::openUrl (mURL)));
3968 }
3969
3970 ServiceClient &mClient;
3971 const QString &mURL;
3972 };
3973
3974 ServiceClient client;
3975 ServiceServer server (client, aURL);
3976 server.start();
3977 client.exec();
3978 server.wait();
3979
3980 bool result = client.result();
3981
3982 if (!result)
3983 msgCenter().cannotOpenURL (aURL);
3984
3985 return result;
3986}
3987
3988/**
3989 * Shows the VirtualBox registration dialog.
3990 *
3991 * @note that this method is not part of UIMessageCenter (like e.g.
3992 * UIMessageCenter::sltShowHelpAboutDialog()) because it is tied to
3993 * VBoxCallback::OnExtraDataChange() handling performed by VBoxGlobal.
3994 *
3995 * @param aForce
3996 */
3997void VBoxGlobal::showRegistrationDialog (bool aForce)
3998{
3999 NOREF(aForce);
4000#ifdef VBOX_WITH_REGISTRATION
4001 if (!aForce && !UIRegistrationWzd::hasToBeShown())
4002 return;
4003
4004 if (mRegDlg)
4005 {
4006 /* Show the already opened registration dialog */
4007 mRegDlg->setWindowState (mRegDlg->windowState() & ~Qt::WindowMinimized);
4008 mRegDlg->raise();
4009 mRegDlg->activateWindow();
4010 }
4011 else
4012 {
4013 /* Store the ID of the main window to ensure that only one
4014 * registration dialog is shown at a time. Due to manipulations with
4015 * OnExtraDataCanChange() and OnExtraDataChange() signals, this extra
4016 * data item acts like an inter-process mutex, so the first process
4017 * that attempts to set it will win, the rest will get a failure from
4018 * the SetExtraData() call. */
4019 mVBox.SetExtraData (GUI_RegistrationDlgWinID,
4020 QString ("%1").arg ((qulonglong) mMainWindow->winId()));
4021
4022 if (mVBox.isOk())
4023 {
4024 /* We've got the "mutex", create a new registration dialog */
4025 UIRegistrationWzd *dlg = new UIRegistrationWzd (&mRegDlg);
4026 dlg->setAttribute (Qt::WA_DeleteOnClose);
4027 Assert (dlg == mRegDlg);
4028 mRegDlg->show();
4029 }
4030 }
4031#endif
4032}
4033
4034void VBoxGlobal::sltGUILanguageChange(QString strLang)
4035{
4036 loadLanguage(strLang);
4037}
4038
4039void VBoxGlobal::sltProcessGlobalSettingChange()
4040{
4041 /* Reload proxy settings: */
4042 reloadProxySettings();
4043}
4044
4045// Protected members
4046////////////////////////////////////////////////////////////////////////////////
4047
4048bool VBoxGlobal::event (QEvent *e)
4049{
4050 switch (e->type())
4051 {
4052 case MediaEnumEventType:
4053 {
4054 VBoxMediaEnumEvent *ev = (VBoxMediaEnumEvent*) e;
4055
4056 if (!ev->mLast)
4057 {
4058 if (ev->mMedium.state() == KMediumState_Inaccessible &&
4059 !ev->mMedium.result().isOk())
4060 msgCenter().cannotGetMediaAccessibility (ev->mMedium);
4061 Assert (ev->mIterator != mMediaList.end());
4062 *(ev->mIterator) = ev->mMedium;
4063 emit mediumEnumerated (*ev->mIterator);
4064 }
4065 else
4066 {
4067 /* the thread has posted the last message, wait for termination */
4068 mMediaEnumThread->wait();
4069 delete mMediaEnumThread;
4070 mMediaEnumThread = 0;
4071 emit mediumEnumFinished (mMediaList);
4072 }
4073
4074 return true;
4075 }
4076
4077 default:
4078 break;
4079 }
4080
4081 return QObject::event (e);
4082}
4083
4084bool VBoxGlobal::eventFilter (QObject *aObject, QEvent *aEvent)
4085{
4086 if (aEvent->type() == QEvent::LanguageChange &&
4087 aObject->isWidgetType() &&
4088 static_cast <QWidget *> (aObject)->isTopLevel())
4089 {
4090 /* Catch the language change event before any other widget gets it in
4091 * order to invalidate cached string resources (like the details view
4092 * templates) that may be used by other widgets. */
4093 QWidgetList list = QApplication::topLevelWidgets();
4094 if (list.first() == aObject)
4095 {
4096 /* call this only once per every language change (see
4097 * QApplication::installTranslator() for details) */
4098 retranslateUi();
4099 }
4100 }
4101
4102 return QObject::eventFilter (aObject, aEvent);
4103}
4104
4105#ifdef VBOX_WITH_DEBUGGER_GUI
4106
4107bool VBoxGlobal::isDebuggerEnabled(CMachine &aMachine)
4108{
4109 return isDebuggerWorker(&mDbgEnabled, aMachine, GUI_DbgEnabled);
4110}
4111
4112bool VBoxGlobal::isDebuggerAutoShowEnabled(CMachine &aMachine)
4113{
4114 return isDebuggerWorker(&mDbgAutoShow, aMachine, GUI_DbgAutoShow);
4115}
4116
4117bool VBoxGlobal::isDebuggerAutoShowCommandLineEnabled(CMachine &aMachine)
4118{
4119 return isDebuggerWorker(&mDbgAutoShowCommandLine, aMachine, GUI_DbgAutoShow);
4120}
4121
4122bool VBoxGlobal::isDebuggerAutoShowStatisticsEnabled(CMachine &aMachine)
4123{
4124 return isDebuggerWorker(&mDbgAutoShowStatistics, aMachine, GUI_DbgAutoShow);
4125}
4126
4127#endif /* VBOX_WITH_DEBUGGER_GUI */
4128
4129// Private members
4130////////////////////////////////////////////////////////////////////////////////
4131
4132bool VBoxGlobal::processArgs()
4133{
4134 bool fResult = false;
4135 QStringList args = qApp->arguments();
4136 QList<QUrl> list;
4137 for (int i = 1; i < args.size(); ++i)
4138 {
4139 /* We break out after the first parameter, cause there could be
4140 parameters with arguments (e.g. --comment comment). */
4141 if (args.at(i).startsWith("-"))
4142 break;
4143#ifdef Q_WS_MAC
4144 QString strArg = ::darwinResolveAlias(args.at(i));
4145#else /* Q_WS_MAC */
4146 QString strArg = args.at(i);
4147#endif /* !Q_WS_MAC */
4148 if ( !strArg.isEmpty()
4149 && QFile::exists(strArg))
4150 list << QUrl::fromLocalFile(strArg);
4151 }
4152 if (!list.isEmpty())
4153 {
4154 for (int i = 0; i < list.size(); ++i)
4155 {
4156 const QString& strFile = list.at(i).toLocalFile();
4157 if (VBoxGlobal::hasAllowedExtension(strFile, VBoxFileExts))
4158 {
4159 CVirtualBox vbox = vboxGlobal().virtualBox();
4160 CMachine machine = vbox.FindMachine(strFile);
4161 if (!machine.isNull())
4162 {
4163 fResult = true;
4164 launchMachine(machine);
4165 /* Remove from the arg list. */
4166 list.removeAll(strFile);
4167 }
4168 }
4169 }
4170 }
4171 if (!list.isEmpty())
4172 {
4173 m_ArgUrlList = list;
4174 QTimer::singleShot(0, &vboxGlobal().selectorWnd(), SLOT(sltOpenUrls()));
4175 }
4176 return fResult;
4177}
4178
4179void VBoxGlobal::init()
4180{
4181#ifdef DEBUG
4182 mVerString += " [DEBUG]";
4183#endif
4184
4185 HRESULT rc = COMBase::InitializeCOM(true);
4186 if (FAILED (rc))
4187 {
4188#ifdef VBOX_WITH_XPCOM
4189 if (rc == NS_ERROR_FILE_ACCESS_DENIED)
4190 {
4191 char szHome[RTPATH_MAX] = "";
4192 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
4193 msgCenter().cannotInitUserHome(QString(szHome));
4194 }
4195 else
4196#endif
4197 msgCenter().cannotInitCOM(rc);
4198 return;
4199 }
4200
4201 mVBox.createInstance (CLSID_VirtualBox);
4202 if (!mVBox.isOk())
4203 {
4204 msgCenter().cannotCreateVirtualBox (mVBox);
4205 return;
4206 }
4207 mHost = virtualBox().GetHost();
4208#ifdef VBOX_WITH_CROGL
4209 m3DAvailable = VBoxOglIs3DAccelerationSupported();
4210#else
4211 m3DAvailable = false;
4212#endif
4213
4214 /* create default non-null global settings */
4215 gset = VBoxGlobalSettings (false);
4216
4217 /* try to load global settings */
4218 gset.load (mVBox);
4219 if (!mVBox.isOk() || !gset)
4220 {
4221 msgCenter().cannotLoadGlobalConfig (mVBox, gset.lastError());
4222 return;
4223 }
4224
4225 /* Load the customized language as early as possible to get possible error
4226 * messages translated */
4227 QString sLanguageId = gset.languageId();
4228 if (!sLanguageId.isNull())
4229 loadLanguage (sLanguageId);
4230
4231 retranslateUi();
4232
4233 connect(gEDataEvents, SIGNAL(sigGUILanguageChange(QString)),
4234 this, SLOT(sltGUILanguageChange(QString)));
4235
4236#ifdef VBOX_GUI_WITH_SYSTRAY
4237 {
4238 /* Increase open Fe/Qt4 windows reference count. */
4239 int c = mVBox.GetExtraData (GUI_MainWindowCount).toInt() + 1;
4240 AssertMsgReturnVoid ((c >= 0) || (mVBox.isOk()),
4241 ("Something went wrong with the window reference count!"));
4242 mVBox.SetExtraData (GUI_MainWindowCount, QString ("%1").arg (c));
4243 mIncreasedWindowCounter = mVBox.isOk();
4244 AssertReturnVoid (mIncreasedWindowCounter);
4245 }
4246#endif
4247
4248 /* Initialize guest OS Type list. */
4249 CGuestOSTypeVector coll = mVBox.GetGuestOSTypes();
4250 int osTypeCount = coll.size();
4251 AssertMsg (osTypeCount > 0, ("Number of OS types must not be zero"));
4252 if (osTypeCount > 0)
4253 {
4254 /* Here we assume the 'Other' type is always the first, so we
4255 * remember it and will append it to the list when finished. */
4256 CGuestOSType otherType = coll[0];
4257 QString otherFamilyId (otherType.GetFamilyId());
4258
4259 /* Fill the lists with all the available OS Types except
4260 * the 'Other' type, which will be appended. */
4261 for (int i = 1; i < coll.size(); ++i)
4262 {
4263 CGuestOSType os = coll[i];
4264 QString familyId (os.GetFamilyId());
4265 if (!mFamilyIDs.contains (familyId))
4266 {
4267 mFamilyIDs << familyId;
4268 mTypes << QList <CGuestOSType> ();
4269 }
4270 mTypes [mFamilyIDs.indexOf (familyId)].append (os);
4271 }
4272
4273 /* Append the 'Other' OS Type to the end of list. */
4274 if (!mFamilyIDs.contains (otherFamilyId))
4275 {
4276 mFamilyIDs << otherFamilyId;
4277 mTypes << QList <CGuestOSType> ();
4278 }
4279 mTypes [mFamilyIDs.indexOf (otherFamilyId)].append (otherType);
4280 }
4281
4282 /* Fill in OS type icon dictionary. */
4283 static const char *kOSTypeIcons [][2] =
4284 {
4285 {"Other", ":/os_other.png"},
4286 {"DOS", ":/os_dos.png"},
4287 {"Netware", ":/os_netware.png"},
4288 {"L4", ":/os_l4.png"},
4289 {"Windows31", ":/os_win31.png"},
4290 {"Windows95", ":/os_win95.png"},
4291 {"Windows98", ":/os_win98.png"},
4292 {"WindowsMe", ":/os_winme.png"},
4293 {"WindowsNT4", ":/os_winnt4.png"},
4294 {"Windows2000", ":/os_win2k.png"},
4295 {"WindowsXP", ":/os_winxp.png"},
4296 {"WindowsXP_64", ":/os_winxp_64.png"},
4297 {"Windows2003", ":/os_win2k3.png"},
4298 {"Windows2003_64", ":/os_win2k3_64.png"},
4299 {"WindowsVista", ":/os_winvista.png"},
4300 {"WindowsVista_64", ":/os_winvista_64.png"},
4301 {"Windows2008", ":/os_win2k8.png"},
4302 {"Windows2008_64", ":/os_win2k8_64.png"},
4303 {"Windows7", ":/os_win7.png"},
4304 {"Windows7_64", ":/os_win7_64.png"},
4305 {"Windows8", ":/os_win8.png"},
4306 {"Windows8_64", ":/os_win8_64.png"},
4307 {"WindowsNT", ":/os_win_other.png"},
4308 {"OS2Warp3", ":/os_os2warp3.png"},
4309 {"OS2Warp4", ":/os_os2warp4.png"},
4310 {"OS2Warp45", ":/os_os2warp45.png"},
4311 {"OS2eCS", ":/os_os2ecs.png"},
4312 {"OS2", ":/os_os2_other.png"},
4313 {"Linux22", ":/os_linux22.png"},
4314 {"Linux24", ":/os_linux24.png"},
4315 {"Linux24_64", ":/os_linux24_64.png"},
4316 {"Linux26", ":/os_linux26.png"},
4317 {"Linux26_64", ":/os_linux26_64.png"},
4318 {"ArchLinux", ":/os_archlinux.png"},
4319 {"ArchLinux_64", ":/os_archlinux_64.png"},
4320 {"Debian", ":/os_debian.png"},
4321 {"Debian_64", ":/os_debian_64.png"},
4322 {"OpenSUSE", ":/os_opensuse.png"},
4323 {"OpenSUSE_64", ":/os_opensuse_64.png"},
4324 {"Fedora", ":/os_fedora.png"},
4325 {"Fedora_64", ":/os_fedora_64.png"},
4326 {"Gentoo", ":/os_gentoo.png"},
4327 {"Gentoo_64", ":/os_gentoo_64.png"},
4328 {"Mandriva", ":/os_mandriva.png"},
4329 {"Mandriva_64", ":/os_mandriva_64.png"},
4330 {"RedHat", ":/os_redhat.png"},
4331 {"RedHat_64", ":/os_redhat_64.png"},
4332 {"Turbolinux", ":/os_turbolinux.png"},
4333 {"Turbolinux_64", ":/os_turbolinux_64.png"},
4334 {"Ubuntu", ":/os_ubuntu.png"},
4335 {"Ubuntu_64", ":/os_ubuntu_64.png"},
4336 {"Xandros", ":/os_xandros.png"},
4337 {"Xandros_64", ":/os_xandros_64.png"},
4338 {"Oracle", ":/os_oracle.png"},
4339 {"Oracle_64", ":/os_oracle_64.png"},
4340 {"Linux", ":/os_linux_other.png"},
4341 {"FreeBSD", ":/os_freebsd.png"},
4342 {"FreeBSD_64", ":/os_freebsd_64.png"},
4343 {"OpenBSD", ":/os_openbsd.png"},
4344 {"OpenBSD_64", ":/os_openbsd_64.png"},
4345 {"NetBSD", ":/os_netbsd.png"},
4346 {"NetBSD_64", ":/os_netbsd_64.png"},
4347 {"Solaris", ":/os_solaris.png"},
4348 {"Solaris_64", ":/os_solaris_64.png"},
4349 {"OpenSolaris", ":/os_oraclesolaris.png"},
4350 {"OpenSolaris_64", ":/os_oraclesolaris_64.png"},
4351 {"Solaris11_64", ":/os_oraclesolaris_64.png"},
4352 {"QNX", ":/os_qnx.png"},
4353 {"MacOS", ":/os_macosx.png"},
4354 {"MacOS_64", ":/os_macosx_64.png"},
4355 {"JRockitVE", ":/os_jrockitve.png"},
4356 };
4357 for (uint n = 0; n < SIZEOF_ARRAY (kOSTypeIcons); ++ n)
4358 {
4359 mOsTypeIcons.insert (kOSTypeIcons [n][0],
4360 new QPixmap (kOSTypeIcons [n][1]));
4361 }
4362
4363 /* online/offline snapshot icons */
4364 mOfflineSnapshotIcon = QPixmap (":/offline_snapshot_16px.png");
4365 mOnlineSnapshotIcon = QPixmap (":/online_snapshot_16px.png");
4366
4367 qApp->installEventFilter (this);
4368
4369 /* process command line */
4370
4371 bool bForceSeamless = false;
4372 bool bForceFullscreen = false;
4373
4374 vm_render_mode_str = RTStrDup (virtualBox()
4375 .GetExtraData (GUI_RenderMode).toAscii().constData());
4376
4377#ifdef Q_WS_X11
4378 mIsKWinManaged = X11IsWindowManagerKWin();
4379#endif
4380
4381#ifdef VBOX_WITH_DEBUGGER_GUI
4382# ifdef VBOX_WITH_DEBUGGER_GUI_MENU
4383 initDebuggerVar(&mDbgEnabled, "VBOX_GUI_DBG_ENABLED", GUI_DbgEnabled, true);
4384# else
4385 initDebuggerVar(&mDbgEnabled, "VBOX_GUI_DBG_ENABLED", GUI_DbgEnabled, false);
4386# endif
4387 initDebuggerVar(&mDbgAutoShow, "VBOX_GUI_DBG_AUTO_SHOW", GUI_DbgAutoShow, false);
4388 mDbgAutoShowCommandLine = mDbgAutoShowStatistics = mDbgAutoShow;
4389 mStartPaused = false;
4390#endif
4391
4392 mShowStartVMErrors = true;
4393 bool startVM = false;
4394 QString vmNameOrUuid;
4395
4396 int argc = qApp->argc();
4397 int i = 1;
4398 while (i < argc)
4399 {
4400 const char *arg = qApp->argv() [i];
4401 /* NOTE: the check here must match the corresponding check for the
4402 * options to start a VM in main.cpp and hardenedmain.cpp exactly,
4403 * otherwise there will be weird error messages. */
4404 if ( !::strcmp (arg, "--startvm")
4405 || !::strcmp (arg, "-startvm"))
4406 {
4407 if (++i < argc)
4408 {
4409 vmNameOrUuid = QString (qApp->argv() [i]);
4410 startVM = true;
4411 }
4412 }
4413#ifdef VBOX_GUI_WITH_PIDFILE
4414 else if (!::strcmp(arg, "-pidfile") || !::strcmp(arg, "--pidfile"))
4415 {
4416 if (++i < argc)
4417 m_strPidfile = QString(qApp->argv()[i]);
4418 }
4419#endif /* VBOX_GUI_WITH_PIDFILE */
4420 else if (!::strcmp(arg, "-seamless") || !::strcmp(arg, "--seamless"))
4421 {
4422 bForceSeamless = true;
4423 }
4424 else if (!::strcmp(arg, "-fullscreen") || !::strcmp(arg, "--fullscreen"))
4425 {
4426 bForceFullscreen = true;
4427 }
4428#ifdef VBOX_GUI_WITH_SYSTRAY
4429 else if (!::strcmp (arg, "-systray") || !::strcmp (arg, "--systray"))
4430 {
4431 mIsTrayMenu = true;
4432 }
4433#endif
4434 else if (!::strcmp (arg, "-comment") || !::strcmp (arg, "--comment"))
4435 {
4436 ++i;
4437 }
4438 else if (!::strcmp (arg, "-rmode") || !::strcmp (arg, "--rmode"))
4439 {
4440 if (++i < argc)
4441 vm_render_mode_str = qApp->argv() [i];
4442 }
4443 else if (!::strcmp (arg, "--settingspw"))
4444 {
4445 if (++i < argc)
4446 {
4447 RTStrCopy(mSettingsPw, sizeof(mSettingsPw), qApp->argv() [i]);
4448 mSettingsPwSet = true;
4449 }
4450 }
4451 else if (!::strcmp (arg, "--settingspwfile"))
4452 {
4453 if (++i < argc)
4454 {
4455 size_t cbFile;
4456 char *pszFile = qApp->argv() [i];
4457 bool fStdIn = !::strcmp(pszFile, "stdin");
4458 int vrc = VINF_SUCCESS;
4459 PRTSTREAM pStrm;
4460 if (!fStdIn)
4461 vrc = RTStrmOpen(pszFile, "r", &pStrm);
4462 else
4463 pStrm = g_pStdIn;
4464 if (RT_SUCCESS(vrc))
4465 {
4466 vrc = RTStrmReadEx(pStrm, mSettingsPw, sizeof(mSettingsPw)-1, &cbFile);
4467 if (RT_SUCCESS(vrc))
4468 {
4469 if (cbFile >= sizeof(mSettingsPw)-1)
4470 continue;
4471 else
4472 {
4473 unsigned i;
4474 for (i = 0; i < cbFile && !RT_C_IS_CNTRL(mSettingsPw[i]); i++)
4475 ;
4476 mSettingsPw[i] = '\0';
4477 mSettingsPwSet = true;
4478 }
4479 }
4480 if (!fStdIn)
4481 RTStrmClose(pStrm);
4482 }
4483 }
4484 }
4485 else if (!::strcmp (arg, "--no-startvm-errormsgbox"))
4486 mShowStartVMErrors = false;
4487 else if (!::strcmp(arg, "--disable-patm"))
4488 mDisablePatm = true;
4489 else if (!::strcmp(arg, "--disable-csam"))
4490 mDisableCsam = true;
4491 else if (!::strcmp(arg, "--recompile-supervisor"))
4492 mRecompileSupervisor = true;
4493 else if (!::strcmp(arg, "--recompile-user"))
4494 mRecompileUser = true;
4495 else if (!::strcmp(arg, "--recompile-all"))
4496 mDisablePatm = mDisableCsam = mRecompileSupervisor = mRecompileUser = true;
4497 else if (!::strcmp(arg, "--warp-pct"))
4498 {
4499 if (++i < argc)
4500 mWarpPct = RTStrToUInt32(qApp->argv() [i]);
4501 }
4502#ifdef VBOX_WITH_DEBUGGER_GUI
4503 else if (!::strcmp (arg, "-dbg") || !::strcmp (arg, "--dbg"))
4504 setDebuggerVar(&mDbgEnabled, true);
4505 else if (!::strcmp( arg, "-debug") || !::strcmp (arg, "--debug"))
4506 {
4507 setDebuggerVar(&mDbgEnabled, true);
4508 setDebuggerVar(&mDbgAutoShow, true);
4509 setDebuggerVar(&mDbgAutoShowCommandLine, true);
4510 setDebuggerVar(&mDbgAutoShowStatistics, true);
4511 mStartPaused = true;
4512 }
4513 else if (!::strcmp (arg, "--debug-command-line"))
4514 {
4515 setDebuggerVar(&mDbgEnabled, true);
4516 setDebuggerVar(&mDbgAutoShow, true);
4517 setDebuggerVar(&mDbgAutoShowCommandLine, true);
4518 mStartPaused = true;
4519 }
4520 else if (!::strcmp (arg, "--debug-statistics"))
4521 {
4522 setDebuggerVar(&mDbgEnabled, true);
4523 setDebuggerVar(&mDbgAutoShow, true);
4524 setDebuggerVar(&mDbgAutoShowStatistics, true);
4525 mStartPaused = true;
4526 }
4527 else if (!::strcmp (arg, "-no-debug") || !::strcmp (arg, "--no-debug"))
4528 {
4529 setDebuggerVar(&mDbgEnabled, false);
4530 setDebuggerVar(&mDbgAutoShow, false);
4531 setDebuggerVar(&mDbgAutoShowCommandLine, false);
4532 setDebuggerVar(&mDbgAutoShowStatistics, false);
4533 }
4534 /* Not quite debug options, but they're only useful with the debugger bits. */
4535 else if (!::strcmp (arg, "--start-paused"))
4536 mStartPaused = true;
4537 else if (!::strcmp (arg, "--start-running"))
4538 mStartPaused = false;
4539#endif
4540 /** @todo add an else { msgbox(syntax error); exit(1); } here, pretty please... */
4541 i++;
4542 }
4543
4544 if (startVM)
4545 {
4546 QUuid uuid = QUuid(vmNameOrUuid);
4547 if (!uuid.isNull())
4548 {
4549 vmUuid = vmNameOrUuid;
4550 }
4551 else
4552 {
4553 CMachine m = mVBox.FindMachine (vmNameOrUuid);
4554 if (m.isNull())
4555 {
4556 if (showStartVMErrors())
4557 msgCenter().cannotFindMachineByName (mVBox, vmNameOrUuid);
4558 return;
4559 }
4560 vmUuid = m.GetId();
4561 }
4562 }
4563
4564 if (mSettingsPwSet)
4565 mVBox.SetSettingsSecret(mSettingsPw);
4566
4567 if (bForceSeamless && !vmUuid.isEmpty())
4568 {
4569 mVBox.FindMachine(vmUuid).SetExtraData(GUI_Seamless, "on");
4570 }
4571 else if (bForceFullscreen && !vmUuid.isEmpty())
4572 {
4573 mVBox.FindMachine(vmUuid).SetExtraData(GUI_Fullscreen, "on");
4574 }
4575
4576 vm_render_mode = vboxGetRenderMode (vm_render_mode_str);
4577
4578#ifdef VBOX_WITH_DEBUGGER_GUI
4579 /* setup the debugger gui. */
4580 if (RTEnvExist("VBOX_GUI_NO_DEBUGGER"))
4581 mDbgEnabled = mDbgAutoShow = mDbgAutoShowCommandLine = mDbgAutoShowStatistics = false;
4582 if (mDbgEnabled)
4583 {
4584 RTERRINFOSTATIC ErrInfo;
4585 RTErrInfoInitStatic(&ErrInfo);
4586 int vrc = SUPR3HardenedLdrLoadAppPriv("VBoxDbg", &mhVBoxDbg, RTLDRLOAD_FLAGS_LOCAL, &ErrInfo.Core);
4587 if (RT_FAILURE(vrc))
4588 {
4589 mhVBoxDbg = NIL_RTLDRMOD;
4590 mDbgAutoShow = mDbgAutoShowCommandLine = mDbgAutoShowStatistics = false;
4591 LogRel(("Failed to load VBoxDbg, rc=%Rrc - %s\n", vrc, ErrInfo.Core.pszMsg));
4592 }
4593 }
4594#endif
4595
4596 mValid = true;
4597
4598 UIConverter::prepare();
4599
4600 /* Cache IMedium data.
4601 * There could be no used mediums at all,
4602 * but this method should be run anyway just to enumerate null UIMedium object,
4603 * used by some VBox smart widgets, like VBoxMediaComboBox: */
4604 vboxGlobal().startEnumeratingMedia();
4605
4606 /* Prepare global settings change handler: */
4607 connect(&settings(), SIGNAL(propertyChanged(const char*, const char*)),
4608 this, SLOT(sltProcessGlobalSettingChange()));
4609 /* Handle global settings change for the first time: */
4610 sltProcessGlobalSettingChange();
4611
4612 /* Create action pool: */
4613 if (isVMConsoleProcess())
4614 UIActionPoolRuntime::create();
4615 else
4616 UIActionPoolSelector::create();
4617
4618 /* Create network manager: */
4619 UINetworkManager::create();
4620
4621 /* Schedule update manager: */
4622 UIUpdateManager::schedule();
4623}
4624
4625
4626/** @internal
4627 *
4628 * This method should be never called directly. It is called automatically
4629 * when the application terminates.
4630 */
4631void VBoxGlobal::cleanup()
4632{
4633 /* Shutdown update manager: */
4634 UIUpdateManager::shutdown();
4635
4636 /* Destroy network manager: */
4637 UINetworkManager::destroy();
4638
4639 /* Destroy action pool: */
4640 if (isVMConsoleProcess())
4641 UIActionPoolRuntime::destroy();
4642 else
4643 UIActionPoolSelector::destroy();
4644
4645 /* sanity check */
4646 if (!sVBoxGlobalInCleanup)
4647 {
4648 AssertMsgFailed (("Should never be called directly\n"));
4649 return;
4650 }
4651
4652#ifdef VBOX_GUI_WITH_SYSTRAY
4653 if (mIncreasedWindowCounter)
4654 {
4655 /* Decrease open Fe/Qt4 windows reference count. */
4656 int c = mVBox.GetExtraData (GUI_MainWindowCount).toInt() - 1;
4657 AssertMsg ((c >= 0) || (mVBox.isOk()),
4658 ("Something went wrong with the window reference count!"));
4659 if (c < 0)
4660 c = 0; /* Clean up the mess. */
4661 mVBox.SetExtraData (GUI_MainWindowCount,
4662 (c > 0) ? QString ("%1").arg (c) : NULL);
4663 AssertWrapperOk (mVBox);
4664 if (c == 0)
4665 {
4666 mVBox.SetExtraData (GUI_TrayIconWinID, NULL);
4667 AssertWrapperOk (mVBox);
4668 }
4669 }
4670#endif
4671
4672#ifdef VBOX_GUI_WITH_PIDFILE
4673 deletePidfile();
4674#endif
4675
4676 /* Destroy our event handlers */
4677 UIExtraDataEventHandler::destroy();
4678
4679 /* Cleanup medium enumeration thread: */
4680 if (mMediaEnumThread)
4681 {
4682 /* sVBoxGlobalInCleanup is true here, so just wait for the thread */
4683 mMediaEnumThread->wait();
4684 delete mMediaEnumThread;
4685 mMediaEnumThread = 0;
4686 }
4687
4688#ifdef VBOX_WITH_REGISTRATION
4689 if (mRegDlg)
4690 mRegDlg->close();
4691#endif
4692
4693 if (mSelectorWnd)
4694 delete mSelectorWnd;
4695 if (m_pVirtualMachine)
4696 delete m_pVirtualMachine;
4697
4698 UIConverter::cleanup();
4699
4700 /* ensure CGuestOSType objects are no longer used */
4701 mFamilyIDs.clear();
4702 mTypes.clear();
4703
4704 /* media list contains a lot of CUUnknown, release them */
4705 mMediaList.clear();
4706 /* the last steps to ensure we don't use COM any more */
4707 mHost.detach();
4708 mVBox.detach();
4709
4710 /* There may be VBoxMediaEnumEvent instances still in the message
4711 * queue which reference COM objects. Remove them to release those objects
4712 * before uninitializing the COM subsystem. */
4713 QApplication::removePostedEvents (this);
4714
4715 COMBase::CleanupCOM();
4716
4717 mValid = false;
4718}
4719
4720#ifdef VBOX_WITH_DEBUGGER_GUI
4721
4722# define VBOXGLOBAL_DBG_CFG_VAR_FALSE (0)
4723# define VBOXGLOBAL_DBG_CFG_VAR_TRUE (1)
4724# define VBOXGLOBAL_DBG_CFG_VAR_MASK (1)
4725# define VBOXGLOBAL_DBG_CFG_VAR_CMD_LINE RT_BIT(3)
4726# define VBOXGLOBAL_DBG_CFG_VAR_DONE RT_BIT(4)
4727
4728/**
4729 * Initialize a debugger config variable.
4730 *
4731 * @param piDbgCfgVar The debugger config variable to init.
4732 * @param pszEnvVar The environment variable name relating to this
4733 * variable.
4734 * @param pszExtraDataName The extra data name relating to this variable.
4735 * @param fDefault The default value.
4736 */
4737void VBoxGlobal::initDebuggerVar(int *piDbgCfgVar, const char *pszEnvVar, const char *pszExtraDataName, bool fDefault)
4738{
4739 QString strEnvValue;
4740 char szEnvValue[256];
4741 int rc = RTEnvGetEx(RTENV_DEFAULT, pszEnvVar, szEnvValue, sizeof(szEnvValue), NULL);
4742 if (RT_SUCCESS(rc))
4743 {
4744 strEnvValue = QString::fromUtf8(&szEnvValue[0]).toLower().trimmed();
4745 if (strEnvValue.isEmpty())
4746 strEnvValue = "yes";
4747 }
4748 else if (rc != VERR_ENV_VAR_NOT_FOUND)
4749 strEnvValue = "veto";
4750
4751 QString strExtraValue = mVBox.GetExtraData(pszExtraDataName).toLower().trimmed();
4752 if (strExtraValue.isEmpty())
4753 strExtraValue = QString();
4754
4755 if ( strEnvValue.contains("veto") || strExtraValue.contains("veto"))
4756 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4757 else if (strEnvValue.isNull() && strExtraValue.isNull())
4758 *piDbgCfgVar = fDefault ? VBOXGLOBAL_DBG_CFG_VAR_TRUE : VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4759 else
4760 {
4761 QString *pStr = !strEnvValue.isEmpty() ? &strEnvValue : &strExtraValue;
4762 if ( pStr->startsWith("y") // yes
4763 || pStr->startsWith("e") // enabled
4764 || pStr->startsWith("t") // true
4765 || pStr->startsWith("on")
4766 || pStr->toLongLong() != 0)
4767 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_TRUE;
4768 else if ( pStr->startsWith("n") // o
4769 || pStr->startsWith("d") // disable
4770 || pStr->startsWith("f") // false
4771 || pStr->startsWith("off")
4772 || pStr->contains("veto")
4773 || pStr->toLongLong() == 0)
4774 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4775 else
4776 {
4777 LogFunc(("Ignoring unknown value '%s' for '%s'\n", pStr->toAscii().constData(), pStr == &strEnvValue ? pszEnvVar : pszExtraDataName));
4778 *piDbgCfgVar = fDefault ? VBOXGLOBAL_DBG_CFG_VAR_TRUE : VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4779 }
4780 }
4781}
4782
4783/**
4784 * Set a debugger config variable according according to start up argument.
4785 *
4786 * @param piDbgCfgVar The debugger config variable to set.
4787 * @param fState The value from the command line.
4788 */
4789void VBoxGlobal::setDebuggerVar(int *piDbgCfgVar, bool fState)
4790{
4791 if (!(*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_DONE))
4792 *piDbgCfgVar = (fState ? VBOXGLOBAL_DBG_CFG_VAR_TRUE : VBOXGLOBAL_DBG_CFG_VAR_FALSE)
4793 | VBOXGLOBAL_DBG_CFG_VAR_CMD_LINE;
4794}
4795
4796/**
4797 * Checks the state of a debugger config variable, updating it with the machine
4798 * settings on the first invocation.
4799 *
4800 * @returns true / false.
4801 * @param piDbgCfgVar The debugger config variable to consult.
4802 * @param rMachine Reference to the machine object.
4803 * @param pszExtraDataName The extra data name relating to this variable.
4804 */
4805bool VBoxGlobal::isDebuggerWorker(int *piDbgCfgVar, CMachine &rMachine, const char *pszExtraDataName)
4806{
4807 if (!(*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_DONE) && !rMachine.isNull())
4808 {
4809 QString str = mVBox.GetExtraData(pszExtraDataName).toLower().trimmed();
4810 if (str.contains("veto"))
4811 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4812 else if (str.isEmpty() || (*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_CMD_LINE))
4813 *piDbgCfgVar |= VBOXGLOBAL_DBG_CFG_VAR_DONE;
4814 else if ( str.startsWith("y") // yes
4815 || str.startsWith("e") // enabled
4816 || str.startsWith("t") // true
4817 || str.startsWith("on")
4818 || str.toLongLong() != 0)
4819 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_TRUE;
4820 else if ( str.startsWith("n") // no
4821 || str.startsWith("d") // disable
4822 || str.startsWith("f") // false
4823 || str.toLongLong() == 0)
4824 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4825 else
4826 *piDbgCfgVar |= VBOXGLOBAL_DBG_CFG_VAR_DONE;
4827 }
4828
4829 return (*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_MASK) == VBOXGLOBAL_DBG_CFG_VAR_TRUE;
4830}
4831
4832#endif /* VBOX_WITH_DEBUGGER_GUI */
4833
4834/** @fn vboxGlobal
4835 *
4836 * Shortcut to the static VBoxGlobal::instance() method, for convenience.
4837 */
4838
4839bool VBoxGlobal::switchToMachine(CMachine &machine)
4840{
4841#ifdef Q_WS_MAC
4842 ULONG64 id = machine.ShowConsoleWindow();
4843#else
4844 WId id = (WId) machine.ShowConsoleWindow();
4845#endif
4846 AssertWrapperOk(machine);
4847 if (!machine.isOk())
4848 return false;
4849
4850 /* winId = 0 it means the console window has already done everything
4851 * necessary to implement the "show window" semantics. */
4852 if (id == 0)
4853 return true;
4854
4855#if defined (Q_WS_WIN32) || defined (Q_WS_X11)
4856
4857 return vboxGlobal().activateWindow(id, true);
4858
4859#elif defined (Q_WS_MAC)
4860 /*
4861 * This is just for the case were the other process cannot steal
4862 * the focus from us. It will send us a PSN so we can try.
4863 */
4864 ProcessSerialNumber psn;
4865 psn.highLongOfPSN = id >> 32;
4866 psn.lowLongOfPSN = (UInt32)id;
4867 OSErr rc = ::SetFrontProcess(&psn);
4868 if (!rc)
4869 Log(("GUI: %#RX64 couldn't do SetFrontProcess on itself, the selector (we) had to do it...\n", id));
4870 else
4871 Log(("GUI: Failed to bring %#RX64 to front. rc=%#x\n", id, rc));
4872 return !rc;
4873
4874#endif
4875
4876 return false;
4877
4878 /// @todo Below is the old method of switching to the console window
4879 // based on the process ID of the console process. It should go away
4880 // after the new (callback-based) method is fully tested.
4881#if 0
4882
4883 if (!canSwitchTo())
4884 return false;
4885
4886#if defined (Q_WS_WIN32)
4887
4888 HWND hwnd = mWinId;
4889
4890 /* if there are blockers (modal and modeless dialogs, etc), find the
4891 * topmost one */
4892 HWND hwndAbove = NULL;
4893 do
4894 {
4895 hwndAbove = GetNextWindow(hwnd, GW_HWNDPREV);
4896 HWND hwndOwner;
4897 if (hwndAbove != NULL &&
4898 ((hwndOwner = GetWindow(hwndAbove, GW_OWNER)) == hwnd ||
4899 hwndOwner == hwndAbove))
4900 hwnd = hwndAbove;
4901 else
4902 break;
4903 }
4904 while (1);
4905
4906 /* first, check that the primary window is visible */
4907 if (IsIconic(mWinId))
4908 ShowWindow(mWinId, SW_RESTORE);
4909 else if (!IsWindowVisible(mWinId))
4910 ShowWindow(mWinId, SW_SHOW);
4911
4912#if 0
4913 LogFlowFunc(("mWinId=%08X hwnd=%08X\n", mWinId, hwnd));
4914#endif
4915
4916 /* then, activate the topmost in the group */
4917 AllowSetForegroundWindow(m_pid);
4918 SetForegroundWindow(hwnd);
4919
4920 return true;
4921
4922#elif defined (Q_WS_X11)
4923
4924 return false;
4925
4926#elif defined (Q_WS_MAC)
4927
4928 ProcessSerialNumber psn;
4929 OSStatus rc = ::GetProcessForPID(m_pid, &psn);
4930 if (!rc)
4931 {
4932 rc = ::SetFrontProcess(&psn);
4933
4934 if (!rc)
4935 {
4936 ShowHideProcess(&psn, true);
4937 return true;
4938 }
4939 }
4940 return false;
4941
4942#else
4943
4944 return false;
4945
4946#endif
4947
4948#endif
4949}
4950
4951bool VBoxGlobal::launchMachine(CMachine &machine, bool fHeadless /* = false */)
4952{
4953 if (machine.CanShowConsoleWindow())
4954 return VBoxGlobal::switchToMachine(machine);
4955
4956 KMachineState state = machine.GetState(); NOREF(state);
4957 AssertMsg( state == KMachineState_PoweredOff
4958 || state == KMachineState_Saved
4959 || state == KMachineState_Teleported
4960 || state == KMachineState_Aborted
4961 , ("Machine must be PoweredOff/Saved/Aborted (%d)", state));
4962
4963 CVirtualBox vbox = vboxGlobal().virtualBox();
4964 CSession session;
4965 session.createInstance(CLSID_Session);
4966 if (session.isNull())
4967 {
4968 msgCenter().cannotOpenSession(session);
4969 return false;
4970 }
4971
4972#if defined(Q_OS_WIN32)
4973 /* allow the started VM process to make itself the foreground window */
4974 AllowSetForegroundWindow(ASFW_ANY);
4975#endif
4976
4977 QString env;
4978#if defined(Q_WS_X11)
4979 /* make sure the VM process will start on the same display as the Selector */
4980 const char *display = RTEnvGet("DISPLAY");
4981 if (display)
4982 env.append(QString("DISPLAY=%1\n").arg(display));
4983 const char *xauth = RTEnvGet("XAUTHORITY");
4984 if (xauth)
4985 env.append(QString("XAUTHORITY=%1\n").arg(xauth));
4986#endif
4987 const QString strType = fHeadless ? "headless" : "GUI/Qt";
4988
4989 CProgress progress = machine.LaunchVMProcess(session, strType, env);
4990 if ( !vbox.isOk()
4991 || progress.isNull())
4992 {
4993 msgCenter().cannotOpenSession(vbox, machine);
4994 return false;
4995 }
4996
4997 /* Hide the "VM spawning" progress dialog */
4998 /* I hope 1 minute will be enough to spawn any running VM silently, isn't it? */
4999 int iSpawningDuration = 60000;
5000 msgCenter().showModalProgressDialog(progress, machine.GetName(), "", 0, false, iSpawningDuration);
5001 if (progress.GetResultCode() != 0)
5002 msgCenter().cannotOpenSession(vbox, machine, progress);
5003
5004 session.UnlockMachine();
5005
5006 return true;
5007}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use