VirtualBox

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

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

FE/Qt: 6357: Make sure no Mac Sheets with the same parent are used when
there is already one.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 163.6 KB
Line 
1/* $Id: VBoxGlobal.cpp 43104 2012-08-30 14:02:28Z 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 (!mVBox.isOk())
1844 {
1845 msgCenter().cannotOpenSession(mVBox, foundMachine);
1846 session.detach();
1847 }
1848
1849 return session;
1850}
1851
1852/**
1853 * Appends the NULL medium to the media list.
1854 * For using with VBoxGlobal::startEnumeratingMedia() only.
1855 */
1856static void addNullMediumToList (VBoxMediaList &aList, VBoxMediaList::iterator aWhere)
1857{
1858 UIMedium medium;
1859 aList.insert (aWhere, medium);
1860}
1861
1862/**
1863 * Appends the given list of mediums to the media list.
1864 * For using with VBoxGlobal::startEnumeratingMedia() only.
1865 */
1866static void addMediumsToList (const CMediumVector &aVector,
1867 VBoxMediaList &aList,
1868 VBoxMediaList::iterator aWhere,
1869 UIMediumType aType,
1870 UIMedium *aParent = 0)
1871{
1872 VBoxMediaList::iterator first = aWhere;
1873
1874 for (CMediumVector::ConstIterator it = aVector.begin(); it != aVector.end(); ++ it)
1875 {
1876 CMedium cmedium (*it);
1877 UIMedium medium (cmedium, aType, aParent);
1878
1879 /* Search for a proper alphabetic position */
1880 VBoxMediaList::iterator jt = first;
1881 for (; jt != aWhere; ++ jt)
1882 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
1883 break;
1884
1885 aList.insert (jt, medium);
1886
1887 /* Adjust the first item if inserted before it */
1888 if (jt == first)
1889 -- first;
1890 }
1891}
1892
1893/**
1894 * Appends the given list of hard disks and all their children to the media list.
1895 * For using with VBoxGlobal::startEnumeratingMedia() only.
1896 */
1897static void addHardDisksToList (const CMediumVector &aVector,
1898 VBoxMediaList &aList,
1899 VBoxMediaList::iterator aWhere,
1900 UIMedium *aParent = 0)
1901{
1902 VBoxMediaList::iterator first = aWhere;
1903
1904 /* First pass: Add siblings sorted */
1905 for (CMediumVector::ConstIterator it = aVector.begin(); it != aVector.end(); ++ it)
1906 {
1907 CMedium cmedium (*it);
1908 UIMedium medium (cmedium, UIMediumType_HardDisk, aParent);
1909
1910 /* Search for a proper alphabetic position */
1911 VBoxMediaList::iterator jt = first;
1912 for (; jt != aWhere; ++ jt)
1913 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
1914 break;
1915
1916 aList.insert (jt, medium);
1917
1918 /* Adjust the first item if inserted before it */
1919 if (jt == first)
1920 -- first;
1921 }
1922
1923 /* Second pass: Add children */
1924 for (VBoxMediaList::iterator it = first; it != aWhere;)
1925 {
1926 CMediumVector children = (*it).medium().GetChildren();
1927 UIMedium *parent = &(*it);
1928
1929 ++ it; /* go to the next sibling before inserting children */
1930 addHardDisksToList (children, aList, it, parent);
1931 }
1932}
1933
1934/**
1935 * Starts a thread that asynchronously enumerates all currently registered
1936 * media.
1937 *
1938 * Before the enumeration is started, the current media list (a list returned by
1939 * #currentMediaList()) is populated with all registered media and the
1940 * #mediumEnumStarted() signal is emitted. The enumeration thread then walks this
1941 * list, checks for media accessibility and emits #mediumEnumerated() signals of
1942 * each checked medium. When all media are checked, the enumeration thread is
1943 * stopped and the #mediumEnumFinished() signal is emitted.
1944 *
1945 * If the enumeration is already in progress, no new thread is started.
1946 *
1947 * The media list returned by #currentMediaList() is always sorted
1948 * alphabetically by the location attribute and comes in the following order:
1949 * <ol>
1950 * <li>All hard disks. If a hard disk has children, these children
1951 * (alphabetically sorted) immediately follow their parent and therefore
1952 * appear before its next sibling hard disk.</li>
1953 * <li>All CD/DVD images.</li>
1954 * <li>All Floppy images.</li>
1955 * </ol>
1956 *
1957 * Note that #mediumEnumerated() signals are emitted in the same order as
1958 * described above.
1959 *
1960 * @sa #currentMediaList()
1961 * @sa #isMediaEnumerationStarted()
1962 */
1963void VBoxGlobal::startEnumeratingMedia()
1964{
1965 AssertReturnVoid (mValid);
1966
1967 /* check if already started but not yet finished */
1968 if (mMediaEnumThread != NULL)
1969 return;
1970
1971 /* ignore the request during application termination */
1972 if (sVBoxGlobalInCleanup)
1973 return;
1974
1975 /* composes a list of all currently known media & their children */
1976 mMediaList.clear();
1977 addNullMediumToList (mMediaList, mMediaList.end());
1978 addHardDisksToList (mVBox.GetHardDisks(), mMediaList, mMediaList.end());
1979 addMediumsToList (mHost.GetDVDDrives(), mMediaList, mMediaList.end(), UIMediumType_DVD);
1980 addMediumsToList (mVBox.GetDVDImages(), mMediaList, mMediaList.end(), UIMediumType_DVD);
1981 addMediumsToList (mHost.GetFloppyDrives(), mMediaList, mMediaList.end(), UIMediumType_Floppy);
1982 addMediumsToList (mVBox.GetFloppyImages(), mMediaList, mMediaList.end(), UIMediumType_Floppy);
1983
1984 /* enumeration thread class */
1985 class MediaEnumThread : public QThread
1986 {
1987 public:
1988
1989 MediaEnumThread (VBoxMediaList &aList)
1990 : mVector (aList.size())
1991 , mSavedIt (aList.begin())
1992 {
1993 int i = 0;
1994 for (VBoxMediaList::const_iterator it = aList.begin();
1995 it != aList.end(); ++ it)
1996 mVector [i ++] = *it;
1997 }
1998
1999 virtual void run()
2000 {
2001 LogFlow (("MediaEnumThread started.\n"));
2002 COMBase::InitializeCOM(false);
2003
2004 CVirtualBox mVBox = vboxGlobal().virtualBox();
2005 QObject *self = &vboxGlobal();
2006
2007 /* Enumerate the list */
2008 for (int i = 0; i < mVector.size() && !sVBoxGlobalInCleanup; ++ i)
2009 {
2010 mVector [i].blockAndQueryState();
2011 QApplication::
2012 postEvent (self,
2013 new VBoxMediaEnumEvent (mVector [i], mSavedIt));
2014 ++mSavedIt;
2015 }
2016
2017 /* Post the end-of-enumeration event */
2018 if (!sVBoxGlobalInCleanup)
2019 QApplication::postEvent (self, new VBoxMediaEnumEvent (mSavedIt));
2020
2021 COMBase::CleanupCOM();
2022 LogFlow (("MediaEnumThread finished.\n"));
2023 }
2024
2025 private:
2026
2027 QVector <UIMedium> mVector;
2028 VBoxMediaList::iterator mSavedIt;
2029 };
2030
2031 mMediaEnumThread = new MediaEnumThread (mMediaList);
2032 AssertReturnVoid (mMediaEnumThread);
2033
2034 /* emit mediumEnumStarted() after we set mMediaEnumThread to != NULL
2035 * to cause isMediaEnumerationStarted() to return TRUE from slots */
2036 emit mediumEnumStarted();
2037
2038 mMediaEnumThread->start();
2039}
2040
2041void VBoxGlobal::reloadProxySettings()
2042{
2043 UIProxyManager proxyManager(settings().proxySettings());
2044 if (proxyManager.proxyEnabled())
2045 {
2046 QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::HttpProxy,
2047 proxyManager.proxyHost(),
2048 proxyManager.proxyPort().toInt(),
2049 proxyManager.authEnabled() ? proxyManager.authLogin() : QString(),
2050 proxyManager.authEnabled() ? proxyManager.authPassword() : QString()));
2051 }
2052 else
2053 {
2054 QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::NoProxy));
2055 }
2056}
2057
2058/**
2059 * Adds a new medium to the current media list and emits the #mediumAdded()
2060 * signal.
2061 *
2062 * @sa #currentMediaList()
2063 */
2064void VBoxGlobal::addMedium (const UIMedium &aMedium)
2065{
2066 /* Note that we maintain the same order here as #startEnumeratingMedia() */
2067
2068 VBoxMediaList::iterator it = mMediaList.begin();
2069
2070 if (aMedium.type() == UIMediumType_HardDisk)
2071 {
2072 VBoxMediaList::iterator itParent = mMediaList.end();
2073
2074 for (; it != mMediaList.end(); ++ it)
2075 {
2076 /* skip null medium that come first */
2077 if ((*it).isNull()) continue;
2078
2079 if ((*it).type() != UIMediumType_HardDisk)
2080 break;
2081
2082 if (aMedium.parent() != NULL && itParent == mMediaList.end())
2083 {
2084 if (&*it == aMedium.parent())
2085 itParent = it;
2086 }
2087 else
2088 {
2089 /* break if met a parent's sibling (will insert before it) */
2090 if (aMedium.parent() != NULL &&
2091 (*it).parent() == (*itParent).parent())
2092 break;
2093
2094 /* compare to aMedium's siblings */
2095 if ((*it).parent() == aMedium.parent() &&
2096 (*it).name().localeAwareCompare (aMedium.name()) > 0)
2097 break;
2098 }
2099 }
2100
2101 AssertReturnVoid (aMedium.parent() == NULL || itParent != mMediaList.end());
2102 }
2103 else
2104 {
2105 for (; it != mMediaList.end(); ++ it)
2106 {
2107 /* skip null medium that come first */
2108 if ((*it).isNull()) continue;
2109
2110 /* skip HardDisks that come first */
2111 if ((*it).type() == UIMediumType_HardDisk)
2112 continue;
2113
2114 /* skip DVD when inserting Floppy */
2115 if (aMedium.type() == UIMediumType_Floppy &&
2116 (*it).type() == UIMediumType_DVD)
2117 continue;
2118
2119 if ((*it).name().localeAwareCompare (aMedium.name()) > 0 ||
2120 (aMedium.type() == UIMediumType_DVD &&
2121 (*it).type() == UIMediumType_Floppy))
2122 break;
2123 }
2124 }
2125
2126 it = mMediaList.insert (it, aMedium);
2127
2128 emit mediumAdded (*it);
2129}
2130
2131/**
2132 * Updates the medium in the current media list and emits the #mediumUpdated()
2133 * signal.
2134 *
2135 * @sa #currentMediaList()
2136 */
2137void VBoxGlobal::updateMedium (const UIMedium &aMedium)
2138{
2139 VBoxMediaList::Iterator it;
2140 for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2141 if ((*it).id() == aMedium.id())
2142 break;
2143
2144 AssertReturnVoid (it != mMediaList.end());
2145
2146 if (&*it != &aMedium)
2147 *it = aMedium;
2148
2149 emit mediumUpdated (*it);
2150}
2151
2152/**
2153 * Removes the medium from the current media list and emits the #mediumRemoved()
2154 * signal.
2155 *
2156 * @sa #currentMediaList()
2157 */
2158void VBoxGlobal::removeMedium (UIMediumType aType, const QString &aId)
2159{
2160 VBoxMediaList::Iterator it;
2161 for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2162 if ((*it).id() == aId)
2163 break;
2164
2165 AssertReturnVoid (it != mMediaList.end());
2166
2167#if DEBUG
2168 /* sanity: must be no children */
2169 {
2170 VBoxMediaList::Iterator jt = it;
2171 ++ jt;
2172 AssertReturnVoid (jt == mMediaList.end() || (*jt).parent() != &*it);
2173 }
2174#endif
2175
2176 UIMedium *pParent = (*it).parent();
2177
2178 /* remove the medium from the list to keep it in sync with the server "for
2179 * free" when the medium is deleted from one of our UIs */
2180 mMediaList.erase (it);
2181
2182 emit mediumRemoved (aType, aId);
2183
2184 /* also emit the parent update signal because some attributes like
2185 * isReadOnly() may have been changed after child removal */
2186 if (pParent != NULL)
2187 {
2188 pParent->refresh();
2189 emit mediumUpdated (*pParent);
2190 }
2191}
2192
2193/**
2194 * Searches for a VBoxMedum object representing the given COM medium object.
2195 *
2196 * @return true if found and false otherwise.
2197 */
2198bool VBoxGlobal::findMedium (const CMedium &aObj, UIMedium &aMedium) const
2199{
2200 for (VBoxMediaList::ConstIterator it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2201 {
2202 if (((*it).medium().isNull() && aObj.isNull()) ||
2203 (!(*it).medium().isNull() && !aObj.isNull() && (*it).medium().GetId() == aObj.GetId()))
2204 {
2205 aMedium = (*it);
2206 return true;
2207 }
2208 }
2209 return false;
2210}
2211
2212/**
2213 * Searches for a VBoxMedum object with the given medium id attribute.
2214 *
2215 * @return VBoxMedum if found which is invalid otherwise.
2216 */
2217UIMedium VBoxGlobal::findMedium (const QString &aMediumId) const
2218{
2219 for (VBoxMediaList::ConstIterator it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2220 if ((*it).id() == aMediumId)
2221 return *it;
2222 return UIMedium();
2223}
2224
2225/* Open some external medium using file open dialog
2226 * and temporary cache (enumerate) it in GUI inner mediums cache: */
2227QString VBoxGlobal::openMediumWithFileOpenDialog(UIMediumType mediumType, QWidget *pParent,
2228 const QString &strDefaultFolder /* = QString() */,
2229 bool fUseLastFolder /* = false */)
2230{
2231 /* Initialize variables: */
2232 QList < QPair <QString, QString> > filters;
2233 QStringList backends;
2234 QStringList prefixes;
2235 QString strFilter;
2236 QString strTitle;
2237 QString allType;
2238 QString strLastFolder;
2239 switch (mediumType)
2240 {
2241 case UIMediumType_HardDisk:
2242 {
2243 filters = vboxGlobal().HDDBackends();
2244 strTitle = tr("Please choose a virtual hard drive file");
2245 allType = tr("All virtual hard drive files (%1)");
2246 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderHD);
2247 if (strLastFolder.isEmpty())
2248 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderCD);
2249 if (strLastFolder.isEmpty())
2250 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderFD);
2251 break;
2252 }
2253 case UIMediumType_DVD:
2254 {
2255 filters = vboxGlobal().DVDBackends();
2256 strTitle = tr("Please choose a virtual optical disk file");
2257 allType = tr("All virtual optical disk files (%1)");
2258 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderCD);
2259 if (strLastFolder.isEmpty())
2260 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderHD);
2261 if (strLastFolder.isEmpty())
2262 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderFD);
2263 break;
2264 }
2265 case UIMediumType_Floppy:
2266 {
2267 filters = vboxGlobal().FloppyBackends();
2268 strTitle = tr("Please choose a virtual floppy disk file");
2269 allType = tr("All virtual floppy disk files (%1)");
2270 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderFD);
2271 if (strLastFolder.isEmpty())
2272 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderCD);
2273 if (strLastFolder.isEmpty())
2274 strLastFolder = virtualBox().GetExtraData(GUI_RecentFolderHD);
2275 break;
2276 }
2277 default:
2278 break;
2279 }
2280 QString strHomeFolder = fUseLastFolder && !strLastFolder.isEmpty() ? strLastFolder :
2281 strDefaultFolder.isEmpty() ? vboxGlobal().virtualBox().GetHomeFolder() : strDefaultFolder;
2282
2283 /* Prepare filters and backends: */
2284 for (int i = 0; i < filters.count(); ++i)
2285 {
2286 /* Get iterated filter: */
2287 QPair <QString, QString> item = filters.at(i);
2288 /* Create one backend filter string: */
2289 backends << QString("%1 (%2)").arg(item.first).arg(item.second);
2290 /* Save the suffix's for the "All" entry: */
2291 prefixes << item.second;
2292 }
2293 if (!prefixes.isEmpty())
2294 backends.insert(0, allType.arg(prefixes.join(" ").trimmed()));
2295 backends << tr("All files (*)");
2296 strFilter = backends.join(";;").trimmed();
2297
2298 /* Create open file dialog: */
2299 QStringList files = QIFileDialog::getOpenFileNames(strHomeFolder, strFilter, pParent, strTitle, 0, true, true);
2300
2301 /* If dialog has some result: */
2302 if (!files.empty() && !files[0].isEmpty())
2303 return openMedium(mediumType, files[0], pParent);
2304
2305 return QString();
2306}
2307
2308QString VBoxGlobal::openMedium(UIMediumType mediumType, QString strMediumLocation, QWidget *pParent /* = 0*/)
2309{
2310 /* Convert to native separators: */
2311 strMediumLocation = QDir::toNativeSeparators(strMediumLocation);
2312
2313 /* Initialize variables: */
2314 CVirtualBox vbox = vboxGlobal().virtualBox();
2315
2316 /* Remember the path of the last chosen medium: */
2317 QString strRecentFolderKey = mediumType == UIMediumType_HardDisk ? GUI_RecentFolderHD :
2318 mediumType == UIMediumType_DVD ? GUI_RecentFolderCD :
2319 mediumType == UIMediumType_Floppy ? GUI_RecentFolderFD :
2320 QString();
2321 vbox.SetExtraData(strRecentFolderKey, QFileInfo(strMediumLocation).absolutePath());
2322
2323 /* Update recently used list: */
2324 QString strRecentListKey = mediumType == UIMediumType_HardDisk ? GUI_RecentListHD :
2325 mediumType == UIMediumType_DVD ? GUI_RecentListCD :
2326 mediumType == UIMediumType_Floppy ? GUI_RecentListFD :
2327 QString();
2328 QStringList recentMediumList = vbox.GetExtraData(strRecentListKey).split(';');
2329 if (recentMediumList.contains(strMediumLocation))
2330 recentMediumList.removeAll(strMediumLocation);
2331 recentMediumList.prepend(strMediumLocation);
2332 while(recentMediumList.size() > 5) recentMediumList.removeLast();
2333 vbox.SetExtraData(strRecentListKey, recentMediumList.join(";"));
2334
2335 /* Open corresponding medium: */
2336 CMedium comMedium = vbox.OpenMedium(strMediumLocation, mediumTypeToGlobal(mediumType), KAccessMode_ReadWrite, false);
2337
2338 if (vbox.isOk())
2339 {
2340 /* Prepare vbox medium wrapper: */
2341 UIMedium vboxMedium;
2342
2343 /* First of all we should test if that medium already opened: */
2344 if (!vboxGlobal().findMedium(comMedium, vboxMedium))
2345 {
2346 /* And create new otherwise: */
2347 vboxMedium = UIMedium(CMedium(comMedium), mediumType, KMediumState_Created);
2348 vboxGlobal().addMedium(vboxMedium);
2349 }
2350
2351 /* Return vboxMedium id: */
2352 return vboxMedium.id();
2353 }
2354 else
2355 msgCenter().cannotOpenMedium(pParent, vbox, mediumType, strMediumLocation);
2356
2357 return QString();
2358}
2359
2360#ifdef VBOX_GUI_WITH_SYSTRAY
2361/**
2362 * Returns the number of current running Fe/Qt4 main windows.
2363 *
2364 * @return Number of running main windows.
2365 */
2366int VBoxGlobal::mainWindowCount ()
2367{
2368 return mVBox.GetExtraData (GUI_MainWindowCount).toInt();
2369}
2370#endif
2371
2372/**
2373 * Native language name of the currently installed translation.
2374 * Returns "English" if no translation is installed
2375 * or if the translation file is invalid.
2376 */
2377QString VBoxGlobal::languageName() const
2378{
2379
2380 return qApp->translate ("@@@", "English",
2381 "Native language name");
2382}
2383
2384/**
2385 * Native language country name of the currently installed translation.
2386 * Returns "--" if no translation is installed or if the translation file is
2387 * invalid, or if the language is independent on the country.
2388 */
2389QString VBoxGlobal::languageCountry() const
2390{
2391 return qApp->translate ("@@@", "--",
2392 "Native language country name "
2393 "(empty if this language is for all countries)");
2394}
2395
2396/**
2397 * Language name of the currently installed translation, in English.
2398 * Returns "English" if no translation is installed
2399 * or if the translation file is invalid.
2400 */
2401QString VBoxGlobal::languageNameEnglish() const
2402{
2403
2404 return qApp->translate ("@@@", "English",
2405 "Language name, in English");
2406}
2407
2408/**
2409 * Language country name of the currently installed translation, in English.
2410 * Returns "--" if no translation is installed or if the translation file is
2411 * invalid, or if the language is independent on the country.
2412 */
2413QString VBoxGlobal::languageCountryEnglish() const
2414{
2415 return qApp->translate ("@@@", "--",
2416 "Language country name, in English "
2417 "(empty if native country name is empty)");
2418}
2419
2420/**
2421 * Comma-separated list of authors of the currently installed translation.
2422 * Returns "Oracle Corporation" if no translation is installed or if the
2423 * translation file is invalid, or if the translation is supplied by Oracle
2424 * Corporation
2425 */
2426QString VBoxGlobal::languageTranslators() const
2427{
2428 return qApp->translate ("@@@", "Oracle Corporation",
2429 "Comma-separated list of translators");
2430}
2431
2432/**
2433 * Changes the language of all global string constants according to the
2434 * currently installed translations tables.
2435 */
2436void VBoxGlobal::retranslateUi()
2437{
2438 mDiskTypes_Differencing = tr ("Differencing", "DiskType");
2439
2440 mUserDefinedPortName = tr ("User-defined", "serial port");
2441
2442 mWarningIcon = UIIconPool::defaultIcon(UIIconPool::MessageBoxWarningIcon).pixmap (16, 16);
2443 Assert (!mWarningIcon.isNull());
2444
2445 mErrorIcon = UIIconPool::defaultIcon(UIIconPool::MessageBoxCriticalIcon).pixmap (16, 16);
2446 Assert (!mErrorIcon.isNull());
2447
2448 /* refresh media properties since they contain some translations too */
2449 for (VBoxMediaList::iterator it = mMediaList.begin();
2450 it != mMediaList.end(); ++ it)
2451 it->refresh();
2452
2453#ifdef Q_WS_X11
2454 /* As X11 do not have functionality for providing human readable key names,
2455 * we keep a table of them, which must be updated when the language is changed. */
2456 UIHotKey::retranslateKeyNames();
2457#endif /* Q_WS_X11 */
2458}
2459
2460// public static stuff
2461////////////////////////////////////////////////////////////////////////////////
2462
2463/* static */
2464bool VBoxGlobal::isDOSType (const QString &aOSTypeId)
2465{
2466 if (aOSTypeId.left (3) == "dos" ||
2467 aOSTypeId.left (3) == "win" ||
2468 aOSTypeId.left (3) == "os2")
2469 return true;
2470
2471 return false;
2472}
2473
2474const char *gVBoxLangSubDir = "/nls";
2475const char *gVBoxLangFileBase = "VirtualBox_";
2476const char *gVBoxLangFileExt = ".qm";
2477const char *gVBoxLangIDRegExp = "(([a-z]{2})(?:_([A-Z]{2}))?)|(C)";
2478const char *gVBoxBuiltInLangName = "C";
2479
2480class VBoxTranslator : public QTranslator
2481{
2482public:
2483
2484 VBoxTranslator (QObject *aParent = 0)
2485 : QTranslator (aParent) {}
2486
2487 bool loadFile (const QString &aFileName)
2488 {
2489 QFile file (aFileName);
2490 if (!file.open (QIODevice::ReadOnly))
2491 return false;
2492 mData = file.readAll();
2493 return load ((uchar*) mData.data(), mData.size());
2494 }
2495
2496private:
2497
2498 QByteArray mData;
2499};
2500
2501static VBoxTranslator *sTranslator = 0;
2502static QString sLoadedLangId = gVBoxBuiltInLangName;
2503
2504/**
2505 * Returns the loaded (active) language ID.
2506 * Note that it may not match with VBoxGlobalSettings::languageId() if the
2507 * specified language cannot be loaded.
2508 * If the built-in language is active, this method returns "C".
2509 *
2510 * @note "C" is treated as the built-in language for simplicity -- the C
2511 * locale is used in unix environments as a fallback when the requested
2512 * locale is invalid. This way we don't need to process both the "built_in"
2513 * language and the "C" language (which is a valid environment setting)
2514 * separately.
2515 */
2516/* static */
2517QString VBoxGlobal::languageId()
2518{
2519 return sLoadedLangId;
2520}
2521
2522/**
2523 * Loads the language by language ID.
2524 *
2525 * @param aLangId Language ID in in form of xx_YY. QString::null means the
2526 * system default language.
2527 */
2528/* static */
2529void VBoxGlobal::loadLanguage (const QString &aLangId)
2530{
2531 QString langId = aLangId.isEmpty() ?
2532 VBoxGlobal::systemLanguageId() : aLangId;
2533 QString languageFileName;
2534 QString selectedLangId = gVBoxBuiltInLangName;
2535
2536 /* If C is selected we change it temporary to en. This makes sure any extra
2537 * "en" translation file will be loaded. This is necessary for loading the
2538 * plural forms of some of our translations. */
2539 bool fResetToC = false;
2540 if (langId == "C")
2541 {
2542 langId = "en";
2543 fResetToC = true;
2544 }
2545
2546 char szNlsPath[RTPATH_MAX];
2547 int rc;
2548
2549 rc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
2550 AssertRC (rc);
2551
2552 QString nlsPath = QString(szNlsPath) + gVBoxLangSubDir;
2553 QDir nlsDir (nlsPath);
2554
2555 Assert (!langId.isEmpty());
2556 if (!langId.isEmpty() && langId != gVBoxBuiltInLangName)
2557 {
2558 QRegExp regExp (gVBoxLangIDRegExp);
2559 int pos = regExp.indexIn (langId);
2560 /* the language ID should match the regexp completely */
2561 AssertReturnVoid (pos == 0);
2562
2563 QString lang = regExp.cap (2);
2564
2565 if (nlsDir.exists (gVBoxLangFileBase + langId + gVBoxLangFileExt))
2566 {
2567 languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + langId +
2568 gVBoxLangFileExt);
2569 selectedLangId = langId;
2570 }
2571 else if (nlsDir.exists (gVBoxLangFileBase + lang + gVBoxLangFileExt))
2572 {
2573 languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + lang +
2574 gVBoxLangFileExt);
2575 selectedLangId = lang;
2576 }
2577 else
2578 {
2579 /* Never complain when the default language is requested. In any
2580 * case, if no explicit language file exists, we will simply
2581 * fall-back to English (built-in). */
2582 if (!aLangId.isNull() && langId != "en")
2583 msgCenter().cannotFindLanguage (langId, nlsPath);
2584 /* selectedLangId remains built-in here */
2585 AssertReturnVoid (selectedLangId == gVBoxBuiltInLangName);
2586 }
2587 }
2588
2589 /* delete the old translator if there is one */
2590 if (sTranslator)
2591 {
2592 /* QTranslator destructor will call qApp->removeTranslator() for
2593 * us. It will also delete all its child translations we attach to it
2594 * below, so we don't have to care about them specially. */
2595 delete sTranslator;
2596 }
2597
2598 /* load new language files */
2599 sTranslator = new VBoxTranslator (qApp);
2600 Assert (sTranslator);
2601 bool loadOk = true;
2602 if (sTranslator)
2603 {
2604 if (selectedLangId != gVBoxBuiltInLangName)
2605 {
2606 Assert (!languageFileName.isNull());
2607 loadOk = sTranslator->loadFile (languageFileName);
2608 }
2609 /* we install the translator in any case: on failure, this will
2610 * activate an empty translator that will give us English
2611 * (built-in) */
2612 qApp->installTranslator (sTranslator);
2613 }
2614 else
2615 loadOk = false;
2616
2617 if (loadOk)
2618 sLoadedLangId = selectedLangId;
2619 else
2620 {
2621 msgCenter().cannotLoadLanguage (languageFileName);
2622 sLoadedLangId = gVBoxBuiltInLangName;
2623 }
2624
2625 /* Try to load the corresponding Qt translation */
2626 if (sLoadedLangId != gVBoxBuiltInLangName)
2627 {
2628#ifdef Q_OS_UNIX
2629 /* We use system installations of Qt on Linux systems, so first, try
2630 * to load the Qt translation from the system location. */
2631 languageFileName = QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" +
2632 sLoadedLangId + gVBoxLangFileExt;
2633 QTranslator *qtSysTr = new QTranslator (sTranslator);
2634 Assert (qtSysTr);
2635 if (qtSysTr && qtSysTr->load (languageFileName))
2636 qApp->installTranslator (qtSysTr);
2637 /* Note that the Qt translation supplied by Oracle is always loaded
2638 * afterwards to make sure it will take precedence over the system
2639 * translation (it may contain more decent variants of translation
2640 * that better correspond to VirtualBox UI). We need to load both
2641 * because a newer version of Qt may be installed on the user computer
2642 * and the Oracle version may not fully support it. We don't do it on
2643 * Win32 because we supply a Qt library there and therefore the
2644 * Oracle translation is always the best one. */
2645#endif
2646 languageFileName = nlsDir.absoluteFilePath (QString ("qt_") +
2647 sLoadedLangId +
2648 gVBoxLangFileExt);
2649 QTranslator *qtTr = new QTranslator (sTranslator);
2650 Assert (qtTr);
2651 if (qtTr && (loadOk = qtTr->load (languageFileName)))
2652 qApp->installTranslator (qtTr);
2653 /* The below message doesn't fit 100% (because it's an additional
2654 * language and the main one won't be reset to built-in on failure)
2655 * but the load failure is so rare here that it's not worth a separate
2656 * message (but still, having something is better than having none) */
2657 if (!loadOk && !aLangId.isNull())
2658 msgCenter().cannotLoadLanguage (languageFileName);
2659 }
2660 if (fResetToC)
2661 sLoadedLangId = "C";
2662#ifdef Q_WS_MAC
2663 /* Qt doesn't translate the items in the Application menu initially.
2664 * Manually trigger an update. */
2665 ::darwinRetranslateAppMenu();
2666#endif /* Q_WS_MAC */
2667}
2668
2669QString VBoxGlobal::helpFile() const
2670{
2671#if defined (Q_WS_WIN32)
2672 const QString name = "VirtualBox";
2673 const QString suffix = "chm";
2674#elif defined (Q_WS_MAC)
2675 const QString name = "UserManual";
2676 const QString suffix = "pdf";
2677#elif defined (Q_WS_X11)
2678# if defined VBOX_OSE
2679 const QString name = "UserManual";
2680 const QString suffix = "pdf";
2681# else
2682 const QString name = "VirtualBox";
2683 const QString suffix = "chm";
2684# endif
2685#endif
2686 /* Where are the docs located? */
2687 char szDocsPath[RTPATH_MAX];
2688 int rc = RTPathAppDocs (szDocsPath, sizeof (szDocsPath));
2689 AssertRC (rc);
2690 /* Make sure that the language is in two letter code.
2691 * Note: if languageId() returns an empty string lang.name() will
2692 * return "C" which is an valid language code. */
2693 QLocale lang (VBoxGlobal::languageId());
2694
2695 /* Construct the path and the filename */
2696 QString manual = QString ("%1/%2_%3.%4").arg (szDocsPath)
2697 .arg (name)
2698 .arg (lang.name())
2699 .arg (suffix);
2700 /* Check if a help file with that name exists */
2701 QFileInfo fi (manual);
2702 if (fi.exists())
2703 return manual;
2704
2705 /* Fall back to the standard */
2706 manual = QString ("%1/%2.%4").arg (szDocsPath)
2707 .arg (name)
2708 .arg (suffix);
2709 return manual;
2710}
2711
2712/**
2713 * Replacement for QToolButton::setTextLabel() that handles the shortcut
2714 * letter (if it is present in the argument string) as if it were a setText()
2715 * call: the shortcut letter is used to automatically assign an "Alt+<letter>"
2716 * accelerator key sequence to the given tool button.
2717 *
2718 * @note This method preserves the icon set if it was assigned before. Only
2719 * the text label and the accelerator are changed.
2720 *
2721 * @param aToolButton Tool button to set the text label on.
2722 * @param aTextLabel Text label to set.
2723 */
2724/* static */
2725void VBoxGlobal::setTextLabel (QToolButton *aToolButton,
2726 const QString &aTextLabel)
2727{
2728 AssertReturnVoid (aToolButton != NULL);
2729
2730 /* remember the icon set as setText() will kill it */
2731 QIcon iset = aToolButton->icon();
2732 /* re-use the setText() method to detect and set the accelerator */
2733 aToolButton->setText (aTextLabel);
2734 QKeySequence accel = aToolButton->shortcut();
2735 aToolButton->setText (aTextLabel);
2736 aToolButton->setIcon (iset);
2737 /* set the accel last as setIconSet() would kill it */
2738 aToolButton->setShortcut (accel);
2739}
2740
2741/**
2742 * Performs direct and flipped search of position for \a aRectangle to make sure
2743 * it is fully contained inside \a aBoundRegion region by moving & resizing
2744 * \a aRectangle if necessary. Selects the minimum shifted result between direct
2745 * and flipped variants.
2746 */
2747/* static */
2748QRect VBoxGlobal::normalizeGeometry (const QRect &aRectangle, const QRegion &aBoundRegion,
2749 bool aCanResize /* = true */)
2750{
2751 /* Direct search for normalized rectangle */
2752 QRect var1 (getNormalized (aRectangle, aBoundRegion, aCanResize));
2753
2754 /* Flipped search for normalized rectangle */
2755 QRect var2 (flip (getNormalized (flip (aRectangle).boundingRect(),
2756 flip (aBoundRegion), aCanResize)).boundingRect());
2757
2758 /* Calculate shift from starting position for both variants */
2759 double length1 = sqrt (pow ((double) (var1.x() - aRectangle.x()), (double) 2) +
2760 pow ((double) (var1.y() - aRectangle.y()), (double) 2));
2761 double length2 = sqrt (pow ((double) (var2.x() - aRectangle.x()), (double) 2) +
2762 pow ((double) (var2.y() - aRectangle.y()), (double) 2));
2763
2764 /* Return minimum shifted variant */
2765 return length1 > length2 ? var2 : var1;
2766}
2767
2768/**
2769 * Ensures that the given rectangle \a aRectangle is fully contained within the
2770 * region \a aBoundRegion by moving \a aRectangle if necessary. If \a aRectangle is
2771 * larger than \a aBoundRegion, top left corner of \a aRectangle is aligned with the
2772 * top left corner of maximum available rectangle and, if \a aCanResize is true,
2773 * \a aRectangle is shrinked to become fully visible.
2774 */
2775/* static */
2776QRect VBoxGlobal::getNormalized (const QRect &aRectangle, const QRegion &aBoundRegion,
2777 bool /* aCanResize = true */)
2778{
2779 /* Storing available horizontal sub-rectangles & vertical shifts */
2780 int windowVertical = aRectangle.center().y();
2781 QVector <QRect> rectanglesVector (aBoundRegion.rects());
2782 QList <QRect> rectanglesList;
2783 QList <int> shiftsList;
2784 foreach (QRect currentItem, rectanglesVector)
2785 {
2786 int currentDelta = qAbs (windowVertical - currentItem.center().y());
2787 int shift2Top = currentItem.top() - aRectangle.top();
2788 int shift2Bot = currentItem.bottom() - aRectangle.bottom();
2789
2790 int itemPosition = 0;
2791 foreach (QRect item, rectanglesList)
2792 {
2793 int delta = qAbs (windowVertical - item.center().y());
2794 if (delta > currentDelta) break; else ++ itemPosition;
2795 }
2796 rectanglesList.insert (itemPosition, currentItem);
2797
2798 int shift2TopPos = 0;
2799 foreach (int shift, shiftsList)
2800 if (qAbs (shift) > qAbs (shift2Top)) break; else ++ shift2TopPos;
2801 shiftsList.insert (shift2TopPos, shift2Top);
2802
2803 int shift2BotPos = 0;
2804 foreach (int shift, shiftsList)
2805 if (qAbs (shift) > qAbs (shift2Bot)) break; else ++ shift2BotPos;
2806 shiftsList.insert (shift2BotPos, shift2Bot);
2807 }
2808
2809 /* Trying to find the appropriate place for window */
2810 QRect result;
2811 for (int i = -1; i < shiftsList.size(); ++ i)
2812 {
2813 /* Move to appropriate vertical */
2814 QRect rectangle (aRectangle);
2815 if (i >= 0) rectangle.translate (0, shiftsList [i]);
2816
2817 /* Search horizontal shift */
2818 int maxShift = 0;
2819 foreach (QRect item, rectanglesList)
2820 {
2821 QRect trectangle (rectangle.translated (item.left() - rectangle.left(), 0));
2822 if (!item.intersects (trectangle))
2823 continue;
2824
2825 if (rectangle.left() < item.left())
2826 {
2827 int shift = item.left() - rectangle.left();
2828 maxShift = qAbs (shift) > qAbs (maxShift) ? shift : maxShift;
2829 }
2830 else if (rectangle.right() > item.right())
2831 {
2832 int shift = item.right() - rectangle.right();
2833 maxShift = qAbs (shift) > qAbs (maxShift) ? shift : maxShift;
2834 }
2835 }
2836
2837 /* Shift across the horizontal direction */
2838 rectangle.translate (maxShift, 0);
2839
2840 /* Check the translated rectangle to feat the rules */
2841 if (aBoundRegion.united (rectangle) == aBoundRegion)
2842 result = rectangle;
2843
2844 if (!result.isNull()) break;
2845 }
2846
2847 if (result.isNull())
2848 {
2849 /* Resize window to feat desirable size
2850 * using max of available rectangles */
2851 QRect maxRectangle;
2852 quint64 maxSquare = 0;
2853 foreach (QRect item, rectanglesList)
2854 {
2855 quint64 square = item.width() * item.height();
2856 if (square > maxSquare)
2857 {
2858 maxSquare = square;
2859 maxRectangle = item;
2860 }
2861 }
2862
2863 result = aRectangle;
2864 result.moveTo (maxRectangle.x(), maxRectangle.y());
2865 if (maxRectangle.right() < result.right())
2866 result.setRight (maxRectangle.right());
2867 if (maxRectangle.bottom() < result.bottom())
2868 result.setBottom (maxRectangle.bottom());
2869 }
2870
2871 return result;
2872}
2873
2874/**
2875 * Returns the flipped (transposed) region.
2876 */
2877/* static */
2878QRegion VBoxGlobal::flip (const QRegion &aRegion)
2879{
2880 QRegion result;
2881 QVector <QRect> rectangles (aRegion.rects());
2882 foreach (QRect rectangle, rectangles)
2883 result += QRect (rectangle.y(), rectangle.x(),
2884 rectangle.height(), rectangle.width());
2885 return result;
2886}
2887
2888/**
2889 * Aligns the center of \a aWidget with the center of \a aRelative.
2890 *
2891 * If necessary, \a aWidget's position is adjusted to make it fully visible
2892 * within the available desktop area. If \a aWidget is bigger then this area,
2893 * it will also be resized unless \a aCanResize is false or there is an
2894 * inappropriate minimum size limit (in which case the top left corner will be
2895 * simply aligned with the top left corner of the available desktop area).
2896 *
2897 * \a aWidget must be a top-level widget. \a aRelative may be any widget, but
2898 * if it's not top-level itself, its top-level widget will be used for
2899 * calculations. \a aRelative can also be NULL, in which case \a aWidget will
2900 * be centered relative to the available desktop area.
2901 */
2902/* static */
2903void VBoxGlobal::centerWidget (QWidget *aWidget, QWidget *aRelative,
2904 bool aCanResize /* = true */)
2905{
2906 AssertReturnVoid (aWidget);
2907 AssertReturnVoid (aWidget->isTopLevel());
2908
2909 QRect deskGeo, parentGeo;
2910 QWidget *w = aRelative;
2911 if (w)
2912 {
2913 w = w->window();
2914 deskGeo = QApplication::desktop()->availableGeometry (w);
2915 parentGeo = w->frameGeometry();
2916 /* On X11/Gnome, geo/frameGeo.x() and y() are always 0 for top level
2917 * widgets with parents, what a shame. Use mapToGlobal() to workaround. */
2918 QPoint d = w->mapToGlobal (QPoint (0, 0));
2919 d.rx() -= w->geometry().x() - w->x();
2920 d.ry() -= w->geometry().y() - w->y();
2921 parentGeo.moveTopLeft (d);
2922 }
2923 else
2924 {
2925 deskGeo = QApplication::desktop()->availableGeometry();
2926 parentGeo = deskGeo;
2927 }
2928
2929 /* On X11, there is no way to determine frame geometry (including WM
2930 * decorations) before the widget is shown for the first time. Stupidly
2931 * enumerate other top level widgets to find the thickest frame. The code
2932 * is based on the idea taken from QDialog::adjustPositionInternal(). */
2933
2934 int extraw = 0, extrah = 0;
2935
2936 QWidgetList list = QApplication::topLevelWidgets();
2937 QListIterator<QWidget*> it (list);
2938 while ((extraw == 0 || extrah == 0) && it.hasNext())
2939 {
2940 int framew, frameh;
2941 QWidget *current = it.next();
2942 if (!current->isVisible())
2943 continue;
2944
2945 framew = current->frameGeometry().width() - current->width();
2946 frameh = current->frameGeometry().height() - current->height();
2947
2948 extraw = qMax (extraw, framew);
2949 extrah = qMax (extrah, frameh);
2950 }
2951
2952 /// @todo (r=dmik) not sure if we really need this
2953#if 0
2954 /* sanity check for decoration frames. With embedding, we
2955 * might get extraordinary values */
2956 if (extraw == 0 || extrah == 0 || extraw > 20 || extrah > 50)
2957 {
2958 extrah = 50;
2959 extraw = 20;
2960 }
2961#endif
2962
2963 /* On non-X11 platforms, the following would be enough instead of the
2964 * above workaround: */
2965 // QRect geo = frameGeometry();
2966 QRect geo = QRect (0, 0, aWidget->width() + extraw,
2967 aWidget->height() + extrah);
2968
2969 geo.moveCenter (QPoint (parentGeo.x() + (parentGeo.width() - 1) / 2,
2970 parentGeo.y() + (parentGeo.height() - 1) / 2));
2971
2972 /* ensure the widget is within the available desktop area */
2973 QRect newGeo = normalizeGeometry (geo, deskGeo, aCanResize);
2974#ifdef Q_WS_MAC
2975 /* No idea why, but Qt doesn't respect if there is a unified toolbar on the
2976 * ::move call. So manually add the height of the toolbar before setting
2977 * the position. */
2978 if (w)
2979 newGeo.translate (0, ::darwinWindowToolBarHeight (aWidget));
2980#endif /* Q_WS_MAC */
2981
2982 aWidget->move (newGeo.topLeft());
2983
2984 if (aCanResize &&
2985 (geo.width() != newGeo.width() || geo.height() != newGeo.height()))
2986 aWidget->resize (newGeo.width() - extraw, newGeo.height() - extrah);
2987}
2988
2989/**
2990 * Returns the decimal separator for the current locale.
2991 */
2992/* static */
2993QChar VBoxGlobal::decimalSep()
2994{
2995 return QLocale::system().decimalPoint();
2996}
2997
2998/**
2999 * Returns the regexp string that defines the format of the human-readable
3000 * size representation, <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
3001 *
3002 * This regexp will capture 5 groups of text:
3003 * - cap(1): integer number in case when no decimal point is present
3004 * (if empty, it means that decimal point is present)
3005 * - cap(2): size suffix in case when no decimal point is present (may be empty)
3006 * - cap(3): integer number in case when decimal point is present (may be empty)
3007 * - cap(4): fraction number (hundredth) in case when decimal point is present
3008 * - cap(5): size suffix in case when decimal point is present (note that
3009 * B cannot appear there)
3010 */
3011/* static */
3012QString VBoxGlobal::sizeRegexp()
3013{
3014 QString regexp =
3015 QString ("^(?:(?:(\\d+)(?:\\s?(%2|%3|%4|%5|%6|%7))?)|(?:(\\d*)%1(\\d{1,2})(?:\\s?(%3|%4|%5|%6|%7))))$")
3016 .arg (decimalSep())
3017 .arg (tr ("B", "size suffix Bytes"))
3018 .arg (tr ("KB", "size suffix KBytes=1024 Bytes"))
3019 .arg (tr ("MB", "size suffix MBytes=1024 KBytes"))
3020 .arg (tr ("GB", "size suffix GBytes=1024 MBytes"))
3021 .arg (tr ("TB", "size suffix TBytes=1024 GBytes"))
3022 .arg (tr ("PB", "size suffix PBytes=1024 TBytes"));
3023 return regexp;
3024}
3025
3026/* static */
3027QString VBoxGlobal::toHumanReadableList(const QStringList &list)
3028{
3029 QString strList;
3030 for (int i = 0; i < list.size(); ++i)
3031 {
3032 strList += list.at(i);
3033 if (i < list.size() - 1)
3034 strList += + " ";
3035 }
3036 return strList;
3037}
3038
3039/**
3040 * Parses the given size string that should be in form of
3041 * <tt>####[.##] B|KB|MB|GB|TB|PB</tt> and returns
3042 * the size value in bytes. Zero is returned on error.
3043 */
3044/* static */
3045quint64 VBoxGlobal::parseSize (const QString &aText)
3046{
3047 QRegExp regexp (sizeRegexp());
3048 int pos = regexp.indexIn (aText);
3049 if (pos != -1)
3050 {
3051 QString intgS = regexp.cap (1);
3052 QString hundS;
3053 QString suff = regexp.cap (2);
3054 if (intgS.isEmpty())
3055 {
3056 intgS = regexp.cap (3);
3057 hundS = regexp.cap (4);
3058 suff = regexp.cap (5);
3059 }
3060
3061 quint64 denom = 0;
3062 if (suff.isEmpty() || suff == tr ("B", "size suffix Bytes"))
3063 denom = 1;
3064 else if (suff == tr ("KB", "size suffix KBytes=1024 Bytes"))
3065 denom = _1K;
3066 else if (suff == tr ("MB", "size suffix MBytes=1024 KBytes"))
3067 denom = _1M;
3068 else if (suff == tr ("GB", "size suffix GBytes=1024 MBytes"))
3069 denom = _1G;
3070 else if (suff == tr ("TB", "size suffix TBytes=1024 GBytes"))
3071 denom = _1T;
3072 else if (suff == tr ("PB", "size suffix PBytes=1024 TBytes"))
3073 denom = _1P;
3074
3075 quint64 intg = intgS.toULongLong();
3076 if (denom == 1)
3077 return intg;
3078
3079 quint64 hund = hundS.leftJustified (2, '0').toULongLong();
3080 hund = hund * denom / 100;
3081 intg = intg * denom + hund;
3082 return intg;
3083 }
3084 else
3085 return 0;
3086}
3087
3088/**
3089 * Formats the given @a aSize value in bytes to a human readable string
3090 * in form of <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
3091 *
3092 * The @a aMode and @a aDecimal parameters are used for rounding the resulting
3093 * number when converting the size value to KB, MB, etc gives a fractional part:
3094 * <ul>
3095 * <li>When \a aMode is FormatSize_Round, the result is rounded to the
3096 * closest number containing \a aDecimal decimal digits.
3097 * </li>
3098 * <li>When \a aMode is FormatSize_RoundDown, the result is rounded to the
3099 * largest number with \a aDecimal decimal digits that is not greater than
3100 * the result. This guarantees that converting the resulting string back to
3101 * the integer value in bytes will not produce a value greater that the
3102 * initial size parameter.
3103 * </li>
3104 * <li>When \a aMode is FormatSize_RoundUp, the result is rounded to the
3105 * smallest number with \a aDecimal decimal digits that is not less than the
3106 * result. This guarantees that converting the resulting string back to the
3107 * integer value in bytes will not produce a value less that the initial
3108 * size parameter.
3109 * </li>
3110 * </ul>
3111 *
3112 * @param aSize Size value in bytes.
3113 * @param aMode Conversion mode.
3114 * @param aDecimal Number of decimal digits in result.
3115 * @return Human-readable size string.
3116 */
3117/* static */
3118QString VBoxGlobal::formatSize (quint64 aSize, uint aDecimal /* = 2 */,
3119 FormatSize aMode /* = FormatSize_Round */)
3120{
3121 static QString Suffixes [7];
3122 Suffixes[0] = tr ("B", "size suffix Bytes");
3123 Suffixes[1] = tr ("KB", "size suffix KBytes=1024 Bytes");
3124 Suffixes[2] = tr ("MB", "size suffix MBytes=1024 KBytes");
3125 Suffixes[3] = tr ("GB", "size suffix GBytes=1024 MBytes");
3126 Suffixes[4] = tr ("TB", "size suffix TBytes=1024 GBytes");
3127 Suffixes[5] = tr ("PB", "size suffix PBytes=1024 TBytes");
3128 Suffixes[6] = (const char *)NULL;
3129 AssertCompile(6 < RT_ELEMENTS (Suffixes));
3130
3131 quint64 denom = 0;
3132 int suffix = 0;
3133
3134 if (aSize < _1K)
3135 {
3136 denom = 1;
3137 suffix = 0;
3138 }
3139 else if (aSize < _1M)
3140 {
3141 denom = _1K;
3142 suffix = 1;
3143 }
3144 else if (aSize < _1G)
3145 {
3146 denom = _1M;
3147 suffix = 2;
3148 }
3149 else if (aSize < _1T)
3150 {
3151 denom = _1G;
3152 suffix = 3;
3153 }
3154 else if (aSize < _1P)
3155 {
3156 denom = _1T;
3157 suffix = 4;
3158 }
3159 else
3160 {
3161 denom = _1P;
3162 suffix = 5;
3163 }
3164
3165 quint64 intg = aSize / denom;
3166 quint64 decm = aSize % denom;
3167 quint64 mult = 1;
3168 for (uint i = 0; i < aDecimal; ++ i) mult *= 10;
3169
3170 QString number;
3171 if (denom > 1)
3172 {
3173 if (decm)
3174 {
3175 decm *= mult;
3176 /* not greater */
3177 if (aMode == FormatSize_RoundDown)
3178 decm = decm / denom;
3179 /* not less */
3180 else if (aMode == FormatSize_RoundUp)
3181 decm = (decm + denom - 1) / denom;
3182 /* nearest */
3183 else decm = (decm + denom / 2) / denom;
3184 }
3185 /* check for the fractional part overflow due to rounding */
3186 if (decm == mult)
3187 {
3188 decm = 0;
3189 ++ intg;
3190 /* check if we've got 1024 XB after rounding and scale down if so */
3191 if (intg == 1024 && Suffixes [suffix + 1] != NULL)
3192 {
3193 intg /= 1024;
3194 ++ suffix;
3195 }
3196 }
3197 number = QString::number (intg);
3198 if (aDecimal) number += QString ("%1%2").arg (decimalSep())
3199 .arg (QString::number (decm).rightJustified (aDecimal, '0'));
3200 }
3201 else
3202 {
3203 number = QString::number (intg);
3204 }
3205
3206 return QString ("%1 %2").arg (number).arg (Suffixes [suffix]);
3207}
3208
3209/**
3210 * Returns the required video memory in bytes for the current desktop
3211 * resolution at maximum possible screen depth in bpp.
3212 */
3213/* static */
3214quint64 VBoxGlobal::requiredVideoMemory(const QString &strGuestOSTypeId, int cMonitors /* = 1 */)
3215{
3216 QDesktopWidget *pDW = QApplication::desktop();
3217 /* We create a list of the size of all available host monitors. This list
3218 * is sorted by value and by starting with the biggest one, we calculate
3219 * the memory requirements for every guest screen. This is of course not
3220 * correct, but as we can't predict on which host screens the user will
3221 * open the guest windows, this is the best assumption we can do, cause it
3222 * is the worst case. */
3223 QVector<int> screenSize(qMax(cMonitors, pDW->numScreens()), 0);
3224 for (int i = 0; i < pDW->numScreens(); ++i)
3225 {
3226 QRect r = pDW->screenGeometry(i);
3227 screenSize[i] = r.width() * r.height();
3228 }
3229 /* Now sort the vector */
3230 qSort(screenSize.begin(), screenSize.end(), qGreater<int>());
3231 /* For the case that there are more guest screens configured then host
3232 * screens available, replace all zeros with the greatest value in the
3233 * vector. */
3234 for (int i = 0; i < screenSize.size(); ++i)
3235 if (screenSize.at(i) == 0)
3236 screenSize.replace(i, screenSize.at(0));
3237
3238 quint64 needBits = 0;
3239 for (int i = 0; i < cMonitors; ++i)
3240 {
3241 /* Calculate summary required memory amount in bits */
3242 needBits += (screenSize.at(i) * /* with x height */
3243 32 + /* we will take the maximum possible bpp for now */
3244 8 * _1M) + /* current cache per screen - may be changed in future */
3245 8 * 4096; /* adapter info */
3246 }
3247 /* Translate value into megabytes with rounding to highest side */
3248 quint64 needMBytes = needBits % (8 * _1M) ? needBits / (8 * _1M) + 1 :
3249 needBits / (8 * _1M) /* convert to megabytes */;
3250
3251 if (strGuestOSTypeId.startsWith("Windows"))
3252 {
3253 /* Windows guests need offscreen VRAM too for graphics acceleration features: */
3254#ifdef VBOX_WITH_CRHGSMI
3255 if (isWddmCompatibleOsType(strGuestOSTypeId))
3256 {
3257 /* wddm mode, there are two surfaces for each screen: shadow & primary */
3258 needMBytes *= 3;
3259 }
3260 else
3261#endif /* VBOX_WITH_CRHGSMI */
3262 {
3263 needMBytes *= 2;
3264 }
3265 }
3266
3267 return needMBytes * _1M;
3268}
3269
3270/**
3271 * Puts soft hyphens after every path component in the given file name.
3272 *
3273 * @param aFileName File name (must be a full path name).
3274 */
3275/* static */
3276QString VBoxGlobal::locationForHTML (const QString &aFileName)
3277{
3278/// @todo (dmik) remove?
3279// QString result = QDir::toNativeSeparators (fn);
3280//#ifdef Q_OS_LINUX
3281// result.replace ('/', "/<font color=red>&shy;</font>");
3282//#else
3283// result.replace ('\\', "\\<font color=red>&shy;</font>");
3284//#endif
3285// return result;
3286 QFileInfo fi (aFileName);
3287 return fi.fileName();
3288}
3289
3290/**
3291 * Reformats the input string @a aStr so that:
3292 * - strings in single quotes will be put inside <nobr> and marked
3293 * with blue color;
3294 * - UUIDs be put inside <nobr> and marked
3295 * with green color;
3296 * - replaces new line chars with </p><p> constructs to form paragraphs
3297 * (note that <p> and </p> are not appended to the beginning and to the
3298 * end of the string respectively, to allow the result be appended
3299 * or prepended to the existing paragraph).
3300 *
3301 * If @a aToolTip is true, colouring is not applied, only the <nobr> tag
3302 * is added. Also, new line chars are replaced with <br> instead of <p>.
3303 */
3304/* static */
3305QString VBoxGlobal::highlight (const QString &aStr, bool aToolTip /* = false */)
3306{
3307 QString strFont;
3308 QString uuidFont;
3309 QString endFont;
3310 if (!aToolTip)
3311 {
3312 strFont = "<font color=#0000CC>";
3313 uuidFont = "<font color=#008000>";
3314 endFont = "</font>";
3315 }
3316
3317 QString text = aStr;
3318
3319 /* replace special entities, '&' -- first! */
3320 text.replace ('&', "&amp;");
3321 text.replace ('<', "&lt;");
3322 text.replace ('>', "&gt;");
3323 text.replace ('\"', "&quot;");
3324
3325 /* mark strings in single quotes with color */
3326 QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
3327 rx.setMinimal (true);
3328 text.replace (rx,
3329 QString ("\\1%1<nobr>'\\2'</nobr>%2").arg (strFont).arg (endFont));
3330
3331 /* mark UUIDs with color */
3332 text.replace (QRegExp (
3333 "((?:^|\\s)[(]?)"
3334 "(\\{[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}\\})"
3335 "(?=[:.-!);]?(?:\\s|$))"),
3336 QString ("\\1%1<nobr>\\2</nobr>%2").arg (uuidFont).arg (endFont));
3337
3338 /* split to paragraphs at \n chars */
3339 if (!aToolTip)
3340 text.replace ('\n', "</p><p>");
3341 else
3342 text.replace ('\n', "<br>");
3343
3344 return text;
3345}
3346
3347/* static */
3348QString VBoxGlobal::replaceHtmlEntities(QString strText)
3349{
3350 return strText
3351 .replace('&', "&amp;")
3352 .replace('<', "&lt;")
3353 .replace('>', "&gt;")
3354 .replace('\"', "&quot;");
3355}
3356
3357/**
3358 * Reformats the input string @a aStr so that:
3359 * - strings in single quotes will be put inside <nobr> and marked
3360 * with bold style;
3361 * - UUIDs be put inside <nobr> and marked
3362 * with italic style;
3363 * - replaces new line chars with </p><p> constructs to form paragraphs
3364 * (note that <p> and </p> are not appended to the beginning and to the
3365 * end of the string respectively, to allow the result be appended
3366 * or prepended to the existing paragraph).
3367 */
3368/* static */
3369QString VBoxGlobal::emphasize (const QString &aStr)
3370{
3371 QString strEmphStart ("<b>");
3372 QString strEmphEnd ("</b>");
3373 QString uuidEmphStart ("<i>");
3374 QString uuidEmphEnd ("</i>");
3375
3376 QString text = aStr;
3377
3378 /* replace special entities, '&' -- first! */
3379 text.replace ('&', "&amp;");
3380 text.replace ('<', "&lt;");
3381 text.replace ('>', "&gt;");
3382 text.replace ('\"', "&quot;");
3383
3384 /* mark strings in single quotes with bold style */
3385 QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
3386 rx.setMinimal (true);
3387 text.replace (rx,
3388 QString ("\\1%1<nobr>'\\2'</nobr>%2").arg (strEmphStart).arg (strEmphEnd));
3389
3390 /* mark UUIDs with italic style */
3391 text.replace (QRegExp (
3392 "((?:^|\\s)[(]?)"
3393 "(\\{[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}\\})"
3394 "(?=[:.-!);]?(?:\\s|$))"),
3395 QString ("\\1%1<nobr>\\2</nobr>%2").arg (uuidEmphStart).arg (uuidEmphEnd));
3396
3397 /* split to paragraphs at \n chars */
3398 text.replace ('\n', "</p><p>");
3399
3400 return text;
3401}
3402
3403/**
3404 * This does exactly the same as QLocale::system().name() but corrects its
3405 * wrong behavior on Linux systems (LC_NUMERIC for some strange reason takes
3406 * precedence over any other locale setting in the QLocale::system()
3407 * implementation). This implementation first looks at LC_ALL (as defined by
3408 * SUS), then looks at LC_MESSAGES which is designed to define a language for
3409 * program messages in case if it differs from the language for other locale
3410 * categories. Then it looks for LANG and finally falls back to
3411 * QLocale::system().name().
3412 *
3413 * The order of precedence is well defined here:
3414 * http://opengroup.org/onlinepubs/007908799/xbd/envvar.html
3415 *
3416 * @note This method will return "C" when the requested locale is invalid or
3417 * when the "C" locale is set explicitly.
3418 */
3419/* static */
3420QString VBoxGlobal::systemLanguageId()
3421{
3422#if defined (Q_WS_MAC)
3423 /* QLocale return the right id only if the user select the format of the
3424 * language also. So we use our own implementation */
3425 return ::darwinSystemLanguage();
3426#elif defined (Q_OS_UNIX)
3427 const char *s = RTEnvGet ("LC_ALL");
3428 if (s == 0)
3429 s = RTEnvGet ("LC_MESSAGES");
3430 if (s == 0)
3431 s = RTEnvGet ("LANG");
3432 if (s != 0)
3433 return QLocale (s).name();
3434#endif
3435 return QLocale::system().name();
3436}
3437
3438#if defined (Q_WS_X11)
3439
3440static char *XXGetProperty (Display *aDpy, Window aWnd,
3441 Atom aPropType, const char *aPropName)
3442{
3443 Atom propNameAtom = XInternAtom (aDpy, aPropName,
3444 True /* only_if_exists */);
3445 if (propNameAtom == None)
3446 return NULL;
3447
3448 Atom actTypeAtom = None;
3449 int actFmt = 0;
3450 unsigned long nItems = 0;
3451 unsigned long nBytesAfter = 0;
3452 unsigned char *propVal = NULL;
3453 int rc = XGetWindowProperty (aDpy, aWnd, propNameAtom,
3454 0, LONG_MAX, False /* delete */,
3455 aPropType, &actTypeAtom, &actFmt,
3456 &nItems, &nBytesAfter, &propVal);
3457 if (rc != Success)
3458 return NULL;
3459
3460 return reinterpret_cast <char *> (propVal);
3461}
3462
3463static Bool XXSendClientMessage (Display *aDpy, Window aWnd, const char *aMsg,
3464 unsigned long aData0 = 0, unsigned long aData1 = 0,
3465 unsigned long aData2 = 0, unsigned long aData3 = 0,
3466 unsigned long aData4 = 0)
3467{
3468 Atom msgAtom = XInternAtom (aDpy, aMsg, True /* only_if_exists */);
3469 if (msgAtom == None)
3470 return False;
3471
3472 XEvent ev;
3473
3474 ev.xclient.type = ClientMessage;
3475 ev.xclient.serial = 0;
3476 ev.xclient.send_event = True;
3477 ev.xclient.display = aDpy;
3478 ev.xclient.window = aWnd;
3479 ev.xclient.message_type = msgAtom;
3480
3481 /* always send as 32 bit for now */
3482 ev.xclient.format = 32;
3483 ev.xclient.data.l [0] = aData0;
3484 ev.xclient.data.l [1] = aData1;
3485 ev.xclient.data.l [2] = aData2;
3486 ev.xclient.data.l [3] = aData3;
3487 ev.xclient.data.l [4] = aData4;
3488
3489 return XSendEvent (aDpy, DefaultRootWindow (aDpy), False,
3490 SubstructureRedirectMask, &ev) != 0;
3491}
3492
3493#endif
3494
3495/**
3496 * Activates the specified window. If necessary, the window will be
3497 * de-iconified activation.
3498 *
3499 * @note On X11, it is implied that @a aWid represents a window of the same
3500 * display the application was started on.
3501 *
3502 * @param aWId Window ID to activate.
3503 * @param aSwitchDesktop @c true to switch to the window's desktop before
3504 * activation.
3505 *
3506 * @return @c true on success and @c false otherwise.
3507 */
3508/* static */
3509bool VBoxGlobal::activateWindow (WId aWId, bool aSwitchDesktop /* = true */)
3510{
3511 bool result = true;
3512
3513#if defined (Q_WS_WIN32)
3514
3515 if (IsIconic (aWId))
3516 result &= !!ShowWindow (aWId, SW_RESTORE);
3517 else if (!IsWindowVisible (aWId))
3518 result &= !!ShowWindow (aWId, SW_SHOW);
3519
3520 result &= !!SetForegroundWindow (aWId);
3521
3522#elif defined (Q_WS_X11)
3523
3524 Display *dpy = QX11Info::display();
3525
3526 if (aSwitchDesktop)
3527 {
3528 /* try to find the desktop ID using the NetWM property */
3529 CARD32 *desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
3530 "_NET_WM_DESKTOP");
3531 if (desktop == NULL)
3532 /* if the NetWM properly is not supported try to find the desktop
3533 * ID using the GNOME WM property */
3534 desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
3535 "_WIN_WORKSPACE");
3536
3537 if (desktop != NULL)
3538 {
3539 Bool ok = XXSendClientMessage (dpy, DefaultRootWindow (dpy),
3540 "_NET_CURRENT_DESKTOP",
3541 *desktop);
3542 if (!ok)
3543 {
3544 LogWarningFunc (("Couldn't switch to desktop=%08X\n",
3545 desktop));
3546 result = false;
3547 }
3548 XFree (desktop);
3549 }
3550 else
3551 {
3552 LogWarningFunc (("Couldn't find a desktop ID for aWId=%08X\n",
3553 aWId));
3554 result = false;
3555 }
3556 }
3557
3558 Bool ok = XXSendClientMessage (dpy, aWId, "_NET_ACTIVE_WINDOW");
3559 result &= !!ok;
3560
3561 XRaiseWindow (dpy, aWId);
3562
3563#else
3564
3565 NOREF (aWId);
3566 NOREF (aSwitchDesktop);
3567 AssertFailed();
3568 result = false;
3569
3570#endif
3571
3572 if (!result)
3573 LogWarningFunc (("Couldn't activate aWId=%08X\n", aWId));
3574
3575 return result;
3576}
3577
3578/**
3579 * Removes the accelerator mark (the ampersand symbol) from the given string
3580 * and returns the result. The string is supposed to be a menu item's text
3581 * that may (or may not) contain the accelerator mark.
3582 *
3583 * In order to support accelerators used in non-alphabet languages
3584 * (e.g. Japanese) that has a form of "(&<L>)" (where <L> is a latin letter),
3585 * this method first searches for this pattern and, if found, removes it as a
3586 * whole. If such a pattern is not found, then the '&' character is simply
3587 * removed from the string.
3588 *
3589 * @note This function removes only the first occurrence of the accelerator
3590 * mark.
3591 *
3592 * @param aText Menu item's text to remove the accelerator mark from.
3593 *
3594 * @return The resulting string.
3595 */
3596/* static */
3597QString VBoxGlobal::removeAccelMark (const QString &aText)
3598{
3599 QString result = aText;
3600
3601 QRegExp accel ("\\(&[a-zA-Z]\\)");
3602 int pos = accel.indexIn (result);
3603 if (pos >= 0)
3604 result.remove (pos, accel.cap().length());
3605 else
3606 {
3607 pos = result.indexOf ('&');
3608 if (pos >= 0)
3609 result.remove (pos, 1);
3610 }
3611
3612 return result;
3613}
3614
3615/* static */
3616QString VBoxGlobal::insertKeyToActionText(const QString &strText, const QString &strKey)
3617{
3618#ifdef Q_WS_MAC
3619 QString pattern("%1 (Host+%2)");
3620#else
3621 QString pattern("%1 \tHost+%2");
3622#endif
3623 if ( strKey.isEmpty()
3624 || strKey.compare("None", Qt::CaseInsensitive) == 0)
3625 return strText;
3626 else
3627 return pattern.arg(strText).arg(QKeySequence(strKey).toString(QKeySequence::NativeText));
3628}
3629
3630/* static */
3631QString VBoxGlobal::extractKeyFromActionText (const QString &aText)
3632{
3633 QString key;
3634#ifdef Q_WS_MAC
3635 QRegExp re (".* \\(Host\\+(.+)\\)");
3636#else
3637 QRegExp re (".* \\t\\Host\\+(.+)");
3638#endif
3639 if (re.exactMatch (aText))
3640 key = re.cap (1);
3641 return key;
3642}
3643
3644/**
3645 * Joins two pixmaps horizontally with 2px space between them and returns the
3646 * result.
3647 *
3648 * @param aPM1 Left pixmap.
3649 * @param aPM2 Right pixmap.
3650 */
3651/* static */
3652QPixmap VBoxGlobal::joinPixmaps (const QPixmap &aPM1, const QPixmap &aPM2)
3653{
3654 if (aPM1.isNull())
3655 return aPM2;
3656 if (aPM2.isNull())
3657 return aPM1;
3658
3659 QPixmap result (aPM1.width() + aPM2.width() + 2,
3660 qMax (aPM1.height(), aPM2.height()));
3661 result.fill (Qt::transparent);
3662
3663 QPainter painter (&result);
3664 painter.drawPixmap (0, 0, aPM1);
3665 painter.drawPixmap (aPM1.width() + 2, result.height() - aPM2.height(), aPM2);
3666 painter.end();
3667
3668 return result;
3669}
3670
3671/**
3672 * Searches for a widget that with @a aName (if it is not NULL) which inherits
3673 * @a aClassName (if it is not NULL) and among children of @a aParent. If @a
3674 * aParent is NULL, all top-level widgets are searched. If @a aRecursive is
3675 * true, child widgets are recursively searched as well.
3676 */
3677/* static */
3678QWidget *VBoxGlobal::findWidget (QWidget *aParent, const char *aName,
3679 const char *aClassName /* = NULL */,
3680 bool aRecursive /* = false */)
3681{
3682 if (aParent == NULL)
3683 {
3684 QWidgetList list = QApplication::topLevelWidgets();
3685 foreach(QWidget *w, list)
3686 {
3687 if ((!aName || strcmp (w->objectName().toAscii().constData(), aName) == 0) &&
3688 (!aClassName || strcmp (w->metaObject()->className(), aClassName) == 0))
3689 return w;
3690 if (aRecursive)
3691 {
3692 w = findWidget (w, aName, aClassName, aRecursive);
3693 if (w)
3694 return w;
3695 }
3696 }
3697 return NULL;
3698 }
3699
3700 /* Find the first children of aParent with the appropriate properties.
3701 * Please note that this call is recursively. */
3702 QList<QWidget *> list = qFindChildren<QWidget *> (aParent, aName);
3703 foreach(QWidget *child, list)
3704 {
3705 if (!aClassName || strcmp (child->metaObject()->className(), aClassName) == 0)
3706 return child;
3707 }
3708 return NULL;
3709}
3710
3711/**
3712 * Figures out which medium formats are currently supported by VirtualBox for
3713 * the given device type.
3714 * Returned is a list of pairs with the form
3715 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3716 */
3717/* static */
3718QList <QPair <QString, QString> > VBoxGlobal::MediumBackends(KDeviceType enmType)
3719{
3720 CSystemProperties systemProperties = vboxGlobal().virtualBox().GetSystemProperties();
3721 QVector<CMediumFormat> mediumFormats = systemProperties.GetMediumFormats();
3722 QList< QPair<QString, QString> > backendPropList;
3723 for (int i = 0; i < mediumFormats.size(); ++ i)
3724 {
3725 /* File extensions */
3726 QVector <QString> fileExtensions;
3727 QVector <KDeviceType> deviceTypes;
3728
3729 mediumFormats [i].DescribeFileExtensions(fileExtensions, deviceTypes);
3730
3731 QStringList f;
3732 for (int a = 0; a < fileExtensions.size(); ++ a)
3733 if (deviceTypes [a] == enmType)
3734 f << QString ("*.%1").arg (fileExtensions [a]);
3735 /* Create a pair out of the backend description and all suffix's. */
3736 if (!f.isEmpty())
3737 backendPropList << QPair<QString, QString> (mediumFormats [i].GetName(), f.join(" "));
3738 }
3739 return backendPropList;
3740}
3741
3742/**
3743 * Figures out which hard disk formats are currently supported by VirtualBox.
3744 * Returned is a list of pairs with the form
3745 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3746 */
3747/* static */
3748QList <QPair <QString, QString> > VBoxGlobal::HDDBackends()
3749{
3750 return MediumBackends(KDeviceType_HardDisk);
3751}
3752
3753/**
3754 * Figures out which CD/DVD disk formats are currently supported by VirtualBox.
3755 * Returned is a list of pairs with the form
3756 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3757 */
3758/* static */
3759QList <QPair <QString, QString> > VBoxGlobal::DVDBackends()
3760{
3761 return MediumBackends(KDeviceType_DVD);
3762}
3763
3764/**
3765 * Figures out which floppy disk formats are currently supported by VirtualBox.
3766 * Returned is a list of pairs with the form
3767 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
3768 */
3769/* static */
3770QList <QPair <QString, QString> > VBoxGlobal::FloppyBackends()
3771{
3772 return MediumBackends(KDeviceType_Floppy);
3773}
3774
3775/* static */
3776QString VBoxGlobal::documentsPath()
3777{
3778 QString path;
3779#if QT_VERSION < 0x040400
3780 path = QDir::homePath();
3781#else
3782 path = QDesktopServices::storageLocation (QDesktopServices::DocumentsLocation);
3783#endif
3784
3785 /* Make sure the path exists */
3786 QDir dir (path);
3787 if (dir.exists())
3788 return QDir::cleanPath (dir.canonicalPath());
3789 else
3790 {
3791 dir.setPath (QDir::homePath() + "/Documents");
3792 if (dir.exists())
3793 return QDir::cleanPath (dir.canonicalPath());
3794 else
3795 return QDir::homePath();
3796 }
3797}
3798
3799#ifdef VBOX_WITH_VIDEOHWACCEL
3800/* static */
3801bool VBoxGlobal::isAcceleration2DVideoAvailable()
3802{
3803 return VBoxQGLOverlay::isAcceleration2DVideoAvailable();
3804}
3805
3806/** additional video memory required for the best 2D support performance
3807 * total amount of VRAM required is thus calculated as requiredVideoMemory + required2DOffscreenVideoMemory */
3808/* static */
3809quint64 VBoxGlobal::required2DOffscreenVideoMemory()
3810{
3811 return VBoxQGLOverlay::required2DOffscreenVideoMemory();
3812}
3813
3814#endif
3815
3816#ifdef VBOX_WITH_CRHGSMI
3817/* static */
3818quint64 VBoxGlobal::required3DWddmOffscreenVideoMemory(const QString &strGuestOSTypeId, int cMonitors /* = 1 */)
3819{
3820 cMonitors = RT_MAX(cMonitors, 1);
3821 quint64 cbSize = VBoxGlobal::requiredVideoMemory(strGuestOSTypeId, 1); /* why not cMonitors? */
3822 cbSize += 64 * _1M;
3823 return cbSize;
3824}
3825
3826/* static */
3827bool VBoxGlobal::isWddmCompatibleOsType(const QString &strGuestOSTypeId)
3828{
3829 return strGuestOSTypeId.startsWith("WindowsVista")
3830 || strGuestOSTypeId.startsWith("Windows7")
3831 || strGuestOSTypeId.startsWith("Windows8")
3832 || strGuestOSTypeId.startsWith("Windows2008");
3833}
3834#endif /* VBOX_WITH_CRHGSMI */
3835
3836#ifdef Q_WS_MAC
3837bool VBoxGlobal::isSheetWindowAllowed(QWidget *pParent) const
3838{
3839 /* Make sure Mac Sheet is not used for the same parent now. */
3840 if (sheetWindowUsed(pParent))
3841 return false;
3842
3843 /* No sheets for fullscreen/seamless now.
3844 * Firstly it looks ugly and secondly in some cases it is broken. */
3845 if (!(qobject_cast<UIMachineWindowFullscreen*>(pParent) ||
3846 qobject_cast<UIMachineWindowSeamless*>(pParent)))
3847 return true;
3848
3849 return false;
3850}
3851
3852void VBoxGlobal::setSheetWindowUsed(QWidget *pParent, bool fUsed)
3853{
3854 if (fUsed)
3855 {
3856 AssertMsg(!m_sheets.contains(pParent), ("Trying to use Mac Sheet for parent which already has one!"));
3857 if (m_sheets.contains(pParent))
3858 return;
3859 }
3860 else
3861 {
3862 AssertMsg(m_sheets.contains(pParent), ("Trying to cancel use Mac Sheet for parent which has no one!"));
3863 if (!m_sheets.contains(pParent))
3864 return;
3865 }
3866
3867 if (fUsed)
3868 m_sheets.insert(pParent);
3869 else
3870 m_sheets.remove(pParent);
3871}
3872
3873bool VBoxGlobal::sheetWindowUsed(QWidget *pParent) const
3874{
3875 return m_sheets.contains(pParent);
3876}
3877#endif /* Q_WS_MAC */
3878
3879/* static */
3880QString VBoxGlobal::fullMediumFormatName(const QString &strBaseMediumFormatName)
3881{
3882 if (strBaseMediumFormatName == "VDI")
3883 return tr("VDI (VirtualBox Disk Image)");
3884 else if (strBaseMediumFormatName == "VMDK")
3885 return tr("VMDK (Virtual Machine Disk)");
3886 else if (strBaseMediumFormatName == "VHD")
3887 return tr("VHD (Virtual Hard Disk)");
3888 else if (strBaseMediumFormatName == "Parallels")
3889 return tr("HDD (Parallels Hard Disk)");
3890 else if (strBaseMediumFormatName == "QED")
3891 return tr("QED (QEMU enhanced disk)");
3892 else if (strBaseMediumFormatName == "QCOW")
3893 return tr("QCOW (QEMU Copy-On-Write)");
3894 return strBaseMediumFormatName;
3895}
3896
3897// Public slots
3898////////////////////////////////////////////////////////////////////////////////
3899
3900/**
3901 * Opens the specified URL using OS/Desktop capabilities.
3902 *
3903 * @param aURL URL to open
3904 *
3905 * @return true on success and false otherwise
3906 */
3907bool VBoxGlobal::openURL (const QString &aURL)
3908{
3909 /* Service event */
3910 class ServiceEvent : public QEvent
3911 {
3912 public:
3913
3914 ServiceEvent (bool aResult) : QEvent (QEvent::User), mResult (aResult) {}
3915
3916 bool result() const { return mResult; }
3917
3918 private:
3919
3920 bool mResult;
3921 };
3922
3923 /* Service-Client object */
3924 class ServiceClient : public QEventLoop
3925 {
3926 public:
3927
3928 ServiceClient() : mResult (false) {}
3929
3930 bool result() const { return mResult; }
3931
3932 private:
3933
3934 bool event (QEvent *aEvent)
3935 {
3936 if (aEvent->type() == QEvent::User)
3937 {
3938 ServiceEvent *pEvent = static_cast <ServiceEvent*> (aEvent);
3939 mResult = pEvent->result();
3940 pEvent->accept();
3941 quit();
3942 return true;
3943 }
3944 return false;
3945 }
3946
3947 bool mResult;
3948 };
3949
3950 /* Service-Server object */
3951 class ServiceServer : public QThread
3952 {
3953 public:
3954
3955 ServiceServer (ServiceClient &aClient, const QString &sURL)
3956 : mClient (aClient), mURL (sURL) {}
3957
3958 private:
3959
3960 void run()
3961 {
3962 QApplication::postEvent (&mClient, new ServiceEvent (QDesktopServices::openUrl (mURL)));
3963 }
3964
3965 ServiceClient &mClient;
3966 const QString &mURL;
3967 };
3968
3969 ServiceClient client;
3970 ServiceServer server (client, aURL);
3971 server.start();
3972 client.exec();
3973 server.wait();
3974
3975 bool result = client.result();
3976
3977 if (!result)
3978 msgCenter().cannotOpenURL (aURL);
3979
3980 return result;
3981}
3982
3983/**
3984 * Shows the VirtualBox registration dialog.
3985 *
3986 * @note that this method is not part of UIMessageCenter (like e.g.
3987 * UIMessageCenter::sltShowHelpAboutDialog()) because it is tied to
3988 * VBoxCallback::OnExtraDataChange() handling performed by VBoxGlobal.
3989 *
3990 * @param aForce
3991 */
3992void VBoxGlobal::showRegistrationDialog (bool aForce)
3993{
3994 NOREF(aForce);
3995#ifdef VBOX_WITH_REGISTRATION
3996 if (!aForce && !UIRegistrationWzd::hasToBeShown())
3997 return;
3998
3999 if (mRegDlg)
4000 {
4001 /* Show the already opened registration dialog */
4002 mRegDlg->setWindowState (mRegDlg->windowState() & ~Qt::WindowMinimized);
4003 mRegDlg->raise();
4004 mRegDlg->activateWindow();
4005 }
4006 else
4007 {
4008 /* Store the ID of the main window to ensure that only one
4009 * registration dialog is shown at a time. Due to manipulations with
4010 * OnExtraDataCanChange() and OnExtraDataChange() signals, this extra
4011 * data item acts like an inter-process mutex, so the first process
4012 * that attempts to set it will win, the rest will get a failure from
4013 * the SetExtraData() call. */
4014 mVBox.SetExtraData (GUI_RegistrationDlgWinID,
4015 QString ("%1").arg ((qulonglong) mMainWindow->winId()));
4016
4017 if (mVBox.isOk())
4018 {
4019 /* We've got the "mutex", create a new registration dialog */
4020 UIRegistrationWzd *dlg = new UIRegistrationWzd (&mRegDlg);
4021 dlg->setAttribute (Qt::WA_DeleteOnClose);
4022 Assert (dlg == mRegDlg);
4023 mRegDlg->show();
4024 }
4025 }
4026#endif
4027}
4028
4029void VBoxGlobal::sltGUILanguageChange(QString strLang)
4030{
4031 loadLanguage(strLang);
4032}
4033
4034void VBoxGlobal::sltProcessGlobalSettingChange()
4035{
4036 /* Reload proxy settings: */
4037 reloadProxySettings();
4038}
4039
4040// Protected members
4041////////////////////////////////////////////////////////////////////////////////
4042
4043bool VBoxGlobal::event (QEvent *e)
4044{
4045 switch (e->type())
4046 {
4047 case MediaEnumEventType:
4048 {
4049 VBoxMediaEnumEvent *ev = (VBoxMediaEnumEvent*) e;
4050
4051 if (!ev->mLast)
4052 {
4053 if (ev->mMedium.state() == KMediumState_Inaccessible &&
4054 !ev->mMedium.result().isOk())
4055 msgCenter().cannotGetMediaAccessibility (ev->mMedium);
4056 Assert (ev->mIterator != mMediaList.end());
4057 *(ev->mIterator) = ev->mMedium;
4058 emit mediumEnumerated (*ev->mIterator);
4059 }
4060 else
4061 {
4062 /* the thread has posted the last message, wait for termination */
4063 mMediaEnumThread->wait();
4064 delete mMediaEnumThread;
4065 mMediaEnumThread = 0;
4066 emit mediumEnumFinished (mMediaList);
4067 }
4068
4069 return true;
4070 }
4071
4072 default:
4073 break;
4074 }
4075
4076 return QObject::event (e);
4077}
4078
4079bool VBoxGlobal::eventFilter (QObject *aObject, QEvent *aEvent)
4080{
4081 if (aEvent->type() == QEvent::LanguageChange &&
4082 aObject->isWidgetType() &&
4083 static_cast <QWidget *> (aObject)->isTopLevel())
4084 {
4085 /* Catch the language change event before any other widget gets it in
4086 * order to invalidate cached string resources (like the details view
4087 * templates) that may be used by other widgets. */
4088 QWidgetList list = QApplication::topLevelWidgets();
4089 if (list.first() == aObject)
4090 {
4091 /* call this only once per every language change (see
4092 * QApplication::installTranslator() for details) */
4093 retranslateUi();
4094 }
4095 }
4096
4097 return QObject::eventFilter (aObject, aEvent);
4098}
4099
4100#ifdef VBOX_WITH_DEBUGGER_GUI
4101
4102bool VBoxGlobal::isDebuggerEnabled(CMachine &aMachine)
4103{
4104 return isDebuggerWorker(&mDbgEnabled, aMachine, GUI_DbgEnabled);
4105}
4106
4107bool VBoxGlobal::isDebuggerAutoShowEnabled(CMachine &aMachine)
4108{
4109 return isDebuggerWorker(&mDbgAutoShow, aMachine, GUI_DbgAutoShow);
4110}
4111
4112bool VBoxGlobal::isDebuggerAutoShowCommandLineEnabled(CMachine &aMachine)
4113{
4114 return isDebuggerWorker(&mDbgAutoShowCommandLine, aMachine, GUI_DbgAutoShow);
4115}
4116
4117bool VBoxGlobal::isDebuggerAutoShowStatisticsEnabled(CMachine &aMachine)
4118{
4119 return isDebuggerWorker(&mDbgAutoShowStatistics, aMachine, GUI_DbgAutoShow);
4120}
4121
4122#endif /* VBOX_WITH_DEBUGGER_GUI */
4123
4124// Private members
4125////////////////////////////////////////////////////////////////////////////////
4126
4127bool VBoxGlobal::processArgs()
4128{
4129 bool fResult = false;
4130 QStringList args = qApp->arguments();
4131 QList<QUrl> list;
4132 for (int i = 1; i < args.size(); ++i)
4133 {
4134 /* We break out after the first parameter, cause there could be
4135 parameters with arguments (e.g. --comment comment). */
4136 if (args.at(i).startsWith("-"))
4137 break;
4138#ifdef Q_WS_MAC
4139 QString strArg = ::darwinResolveAlias(args.at(i));
4140#else /* Q_WS_MAC */
4141 QString strArg = args.at(i);
4142#endif /* !Q_WS_MAC */
4143 if ( !strArg.isEmpty()
4144 && QFile::exists(strArg))
4145 list << QUrl::fromLocalFile(strArg);
4146 }
4147 if (!list.isEmpty())
4148 {
4149 for (int i = 0; i < list.size(); ++i)
4150 {
4151 const QString& strFile = list.at(i).toLocalFile();
4152 if (VBoxGlobal::hasAllowedExtension(strFile, VBoxFileExts))
4153 {
4154 CVirtualBox vbox = vboxGlobal().virtualBox();
4155 CMachine machine = vbox.FindMachine(strFile);
4156 if (!machine.isNull())
4157 {
4158 fResult = true;
4159 launchMachine(machine);
4160 /* Remove from the arg list. */
4161 list.removeAll(strFile);
4162 }
4163 }
4164 }
4165 }
4166 if (!list.isEmpty())
4167 {
4168 m_ArgUrlList = list;
4169 QTimer::singleShot(0, &vboxGlobal().selectorWnd(), SLOT(sltOpenUrls()));
4170 }
4171 return fResult;
4172}
4173
4174void VBoxGlobal::init()
4175{
4176#ifdef DEBUG
4177 mVerString += " [DEBUG]";
4178#endif
4179
4180 HRESULT rc = COMBase::InitializeCOM(true);
4181 if (FAILED (rc))
4182 {
4183#ifdef VBOX_WITH_XPCOM
4184 if (rc == NS_ERROR_FILE_ACCESS_DENIED)
4185 {
4186 char szHome[RTPATH_MAX] = "";
4187 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
4188 msgCenter().cannotInitUserHome(QString(szHome));
4189 }
4190 else
4191#endif
4192 msgCenter().cannotInitCOM(rc);
4193 return;
4194 }
4195
4196 mVBox.createInstance (CLSID_VirtualBox);
4197 if (!mVBox.isOk())
4198 {
4199 msgCenter().cannotCreateVirtualBox (mVBox);
4200 return;
4201 }
4202 mHost = virtualBox().GetHost();
4203#ifdef VBOX_WITH_CROGL
4204 m3DAvailable = VBoxOglIs3DAccelerationSupported();
4205#else
4206 m3DAvailable = false;
4207#endif
4208
4209 /* create default non-null global settings */
4210 gset = VBoxGlobalSettings (false);
4211
4212 /* try to load global settings */
4213 gset.load (mVBox);
4214 if (!mVBox.isOk() || !gset)
4215 {
4216 msgCenter().cannotLoadGlobalConfig (mVBox, gset.lastError());
4217 return;
4218 }
4219
4220 /* Load the customized language as early as possible to get possible error
4221 * messages translated */
4222 QString sLanguageId = gset.languageId();
4223 if (!sLanguageId.isNull())
4224 loadLanguage (sLanguageId);
4225
4226 retranslateUi();
4227
4228 connect(gEDataEvents, SIGNAL(sigGUILanguageChange(QString)),
4229 this, SLOT(sltGUILanguageChange(QString)));
4230
4231#ifdef VBOX_GUI_WITH_SYSTRAY
4232 {
4233 /* Increase open Fe/Qt4 windows reference count. */
4234 int c = mVBox.GetExtraData (GUI_MainWindowCount).toInt() + 1;
4235 AssertMsgReturnVoid ((c >= 0) || (mVBox.isOk()),
4236 ("Something went wrong with the window reference count!"));
4237 mVBox.SetExtraData (GUI_MainWindowCount, QString ("%1").arg (c));
4238 mIncreasedWindowCounter = mVBox.isOk();
4239 AssertReturnVoid (mIncreasedWindowCounter);
4240 }
4241#endif
4242
4243 /* Initialize guest OS Type list. */
4244 CGuestOSTypeVector coll = mVBox.GetGuestOSTypes();
4245 int osTypeCount = coll.size();
4246 AssertMsg (osTypeCount > 0, ("Number of OS types must not be zero"));
4247 if (osTypeCount > 0)
4248 {
4249 /* Here we assume the 'Other' type is always the first, so we
4250 * remember it and will append it to the list when finished. */
4251 CGuestOSType otherType = coll[0];
4252 QString otherFamilyId (otherType.GetFamilyId());
4253
4254 /* Fill the lists with all the available OS Types except
4255 * the 'Other' type, which will be appended. */
4256 for (int i = 1; i < coll.size(); ++i)
4257 {
4258 CGuestOSType os = coll[i];
4259 QString familyId (os.GetFamilyId());
4260 if (!mFamilyIDs.contains (familyId))
4261 {
4262 mFamilyIDs << familyId;
4263 mTypes << QList <CGuestOSType> ();
4264 }
4265 mTypes [mFamilyIDs.indexOf (familyId)].append (os);
4266 }
4267
4268 /* Append the 'Other' OS Type to the end of list. */
4269 if (!mFamilyIDs.contains (otherFamilyId))
4270 {
4271 mFamilyIDs << otherFamilyId;
4272 mTypes << QList <CGuestOSType> ();
4273 }
4274 mTypes [mFamilyIDs.indexOf (otherFamilyId)].append (otherType);
4275 }
4276
4277 /* Fill in OS type icon dictionary. */
4278 static const char *kOSTypeIcons [][2] =
4279 {
4280 {"Other", ":/os_other.png"},
4281 {"DOS", ":/os_dos.png"},
4282 {"Netware", ":/os_netware.png"},
4283 {"L4", ":/os_l4.png"},
4284 {"Windows31", ":/os_win31.png"},
4285 {"Windows95", ":/os_win95.png"},
4286 {"Windows98", ":/os_win98.png"},
4287 {"WindowsMe", ":/os_winme.png"},
4288 {"WindowsNT4", ":/os_winnt4.png"},
4289 {"Windows2000", ":/os_win2k.png"},
4290 {"WindowsXP", ":/os_winxp.png"},
4291 {"WindowsXP_64", ":/os_winxp_64.png"},
4292 {"Windows2003", ":/os_win2k3.png"},
4293 {"Windows2003_64", ":/os_win2k3_64.png"},
4294 {"WindowsVista", ":/os_winvista.png"},
4295 {"WindowsVista_64", ":/os_winvista_64.png"},
4296 {"Windows2008", ":/os_win2k8.png"},
4297 {"Windows2008_64", ":/os_win2k8_64.png"},
4298 {"Windows7", ":/os_win7.png"},
4299 {"Windows7_64", ":/os_win7_64.png"},
4300 {"Windows8", ":/os_win8.png"},
4301 {"Windows8_64", ":/os_win8_64.png"},
4302 {"WindowsNT", ":/os_win_other.png"},
4303 {"OS2Warp3", ":/os_os2warp3.png"},
4304 {"OS2Warp4", ":/os_os2warp4.png"},
4305 {"OS2Warp45", ":/os_os2warp45.png"},
4306 {"OS2eCS", ":/os_os2ecs.png"},
4307 {"OS2", ":/os_os2_other.png"},
4308 {"Linux22", ":/os_linux22.png"},
4309 {"Linux24", ":/os_linux24.png"},
4310 {"Linux24_64", ":/os_linux24_64.png"},
4311 {"Linux26", ":/os_linux26.png"},
4312 {"Linux26_64", ":/os_linux26_64.png"},
4313 {"ArchLinux", ":/os_archlinux.png"},
4314 {"ArchLinux_64", ":/os_archlinux_64.png"},
4315 {"Debian", ":/os_debian.png"},
4316 {"Debian_64", ":/os_debian_64.png"},
4317 {"OpenSUSE", ":/os_opensuse.png"},
4318 {"OpenSUSE_64", ":/os_opensuse_64.png"},
4319 {"Fedora", ":/os_fedora.png"},
4320 {"Fedora_64", ":/os_fedora_64.png"},
4321 {"Gentoo", ":/os_gentoo.png"},
4322 {"Gentoo_64", ":/os_gentoo_64.png"},
4323 {"Mandriva", ":/os_mandriva.png"},
4324 {"Mandriva_64", ":/os_mandriva_64.png"},
4325 {"RedHat", ":/os_redhat.png"},
4326 {"RedHat_64", ":/os_redhat_64.png"},
4327 {"Turbolinux", ":/os_turbolinux.png"},
4328 {"Turbolinux_64", ":/os_turbolinux_64.png"},
4329 {"Ubuntu", ":/os_ubuntu.png"},
4330 {"Ubuntu_64", ":/os_ubuntu_64.png"},
4331 {"Xandros", ":/os_xandros.png"},
4332 {"Xandros_64", ":/os_xandros_64.png"},
4333 {"Oracle", ":/os_oracle.png"},
4334 {"Oracle_64", ":/os_oracle_64.png"},
4335 {"Linux", ":/os_linux_other.png"},
4336 {"FreeBSD", ":/os_freebsd.png"},
4337 {"FreeBSD_64", ":/os_freebsd_64.png"},
4338 {"OpenBSD", ":/os_openbsd.png"},
4339 {"OpenBSD_64", ":/os_openbsd_64.png"},
4340 {"NetBSD", ":/os_netbsd.png"},
4341 {"NetBSD_64", ":/os_netbsd_64.png"},
4342 {"Solaris", ":/os_solaris.png"},
4343 {"Solaris_64", ":/os_solaris_64.png"},
4344 {"OpenSolaris", ":/os_oraclesolaris.png"},
4345 {"OpenSolaris_64", ":/os_oraclesolaris_64.png"},
4346 {"Solaris11_64", ":/os_oraclesolaris_64.png"},
4347 {"QNX", ":/os_qnx.png"},
4348 {"MacOS", ":/os_macosx.png"},
4349 {"MacOS_64", ":/os_macosx_64.png"},
4350 {"JRockitVE", ":/os_jrockitve.png"},
4351 };
4352 for (uint n = 0; n < SIZEOF_ARRAY (kOSTypeIcons); ++ n)
4353 {
4354 mOsTypeIcons.insert (kOSTypeIcons [n][0],
4355 new QPixmap (kOSTypeIcons [n][1]));
4356 }
4357
4358 /* online/offline snapshot icons */
4359 mOfflineSnapshotIcon = QPixmap (":/offline_snapshot_16px.png");
4360 mOnlineSnapshotIcon = QPixmap (":/online_snapshot_16px.png");
4361
4362 qApp->installEventFilter (this);
4363
4364 /* process command line */
4365
4366 bool bForceSeamless = false;
4367 bool bForceFullscreen = false;
4368
4369 vm_render_mode_str = RTStrDup (virtualBox()
4370 .GetExtraData (GUI_RenderMode).toAscii().constData());
4371
4372#ifdef Q_WS_X11
4373 mIsKWinManaged = X11IsWindowManagerKWin();
4374#endif
4375
4376#ifdef VBOX_WITH_DEBUGGER_GUI
4377# ifdef VBOX_WITH_DEBUGGER_GUI_MENU
4378 initDebuggerVar(&mDbgEnabled, "VBOX_GUI_DBG_ENABLED", GUI_DbgEnabled, true);
4379# else
4380 initDebuggerVar(&mDbgEnabled, "VBOX_GUI_DBG_ENABLED", GUI_DbgEnabled, false);
4381# endif
4382 initDebuggerVar(&mDbgAutoShow, "VBOX_GUI_DBG_AUTO_SHOW", GUI_DbgAutoShow, false);
4383 mDbgAutoShowCommandLine = mDbgAutoShowStatistics = mDbgAutoShow;
4384 mStartPaused = false;
4385#endif
4386
4387 mShowStartVMErrors = true;
4388 bool startVM = false;
4389 QString vmNameOrUuid;
4390
4391 int argc = qApp->argc();
4392 int i = 1;
4393 while (i < argc)
4394 {
4395 const char *arg = qApp->argv() [i];
4396 /* NOTE: the check here must match the corresponding check for the
4397 * options to start a VM in main.cpp and hardenedmain.cpp exactly,
4398 * otherwise there will be weird error messages. */
4399 if ( !::strcmp (arg, "--startvm")
4400 || !::strcmp (arg, "-startvm"))
4401 {
4402 if (++i < argc)
4403 {
4404 vmNameOrUuid = QString (qApp->argv() [i]);
4405 startVM = true;
4406 }
4407 }
4408#ifdef VBOX_GUI_WITH_PIDFILE
4409 else if (!::strcmp(arg, "-pidfile") || !::strcmp(arg, "--pidfile"))
4410 {
4411 if (++i < argc)
4412 m_strPidfile = QString(qApp->argv()[i]);
4413 }
4414#endif /* VBOX_GUI_WITH_PIDFILE */
4415 else if (!::strcmp(arg, "-seamless") || !::strcmp(arg, "--seamless"))
4416 {
4417 bForceSeamless = true;
4418 }
4419 else if (!::strcmp(arg, "-fullscreen") || !::strcmp(arg, "--fullscreen"))
4420 {
4421 bForceFullscreen = true;
4422 }
4423#ifdef VBOX_GUI_WITH_SYSTRAY
4424 else if (!::strcmp (arg, "-systray") || !::strcmp (arg, "--systray"))
4425 {
4426 mIsTrayMenu = true;
4427 }
4428#endif
4429 else if (!::strcmp (arg, "-comment") || !::strcmp (arg, "--comment"))
4430 {
4431 ++i;
4432 }
4433 else if (!::strcmp (arg, "-rmode") || !::strcmp (arg, "--rmode"))
4434 {
4435 if (++i < argc)
4436 vm_render_mode_str = qApp->argv() [i];
4437 }
4438 else if (!::strcmp (arg, "--settingspw"))
4439 {
4440 if (++i < argc)
4441 {
4442 RTStrCopy(mSettingsPw, sizeof(mSettingsPw), qApp->argv() [i]);
4443 mSettingsPwSet = true;
4444 }
4445 }
4446 else if (!::strcmp (arg, "--settingspwfile"))
4447 {
4448 if (++i < argc)
4449 {
4450 size_t cbFile;
4451 char *pszFile = qApp->argv() [i];
4452 bool fStdIn = !::strcmp(pszFile, "stdin");
4453 int vrc = VINF_SUCCESS;
4454 PRTSTREAM pStrm;
4455 if (!fStdIn)
4456 vrc = RTStrmOpen(pszFile, "r", &pStrm);
4457 else
4458 pStrm = g_pStdIn;
4459 if (RT_SUCCESS(vrc))
4460 {
4461 vrc = RTStrmReadEx(pStrm, mSettingsPw, sizeof(mSettingsPw)-1, &cbFile);
4462 if (RT_SUCCESS(vrc))
4463 {
4464 if (cbFile >= sizeof(mSettingsPw)-1)
4465 continue;
4466 else
4467 {
4468 unsigned i;
4469 for (i = 0; i < cbFile && !RT_C_IS_CNTRL(mSettingsPw[i]); i++)
4470 ;
4471 mSettingsPw[i] = '\0';
4472 mSettingsPwSet = true;
4473 }
4474 }
4475 if (!fStdIn)
4476 RTStrmClose(pStrm);
4477 }
4478 }
4479 }
4480 else if (!::strcmp (arg, "--no-startvm-errormsgbox"))
4481 mShowStartVMErrors = false;
4482 else if (!::strcmp(arg, "--disable-patm"))
4483 mDisablePatm = true;
4484 else if (!::strcmp(arg, "--disable-csam"))
4485 mDisableCsam = true;
4486 else if (!::strcmp(arg, "--recompile-supervisor"))
4487 mRecompileSupervisor = true;
4488 else if (!::strcmp(arg, "--recompile-user"))
4489 mRecompileUser = true;
4490 else if (!::strcmp(arg, "--recompile-all"))
4491 mDisablePatm = mDisableCsam = mRecompileSupervisor = mRecompileUser = true;
4492 else if (!::strcmp(arg, "--warp-pct"))
4493 {
4494 if (++i < argc)
4495 mWarpPct = RTStrToUInt32(qApp->argv() [i]);
4496 }
4497#ifdef VBOX_WITH_DEBUGGER_GUI
4498 else if (!::strcmp (arg, "-dbg") || !::strcmp (arg, "--dbg"))
4499 setDebuggerVar(&mDbgEnabled, true);
4500 else if (!::strcmp( arg, "-debug") || !::strcmp (arg, "--debug"))
4501 {
4502 setDebuggerVar(&mDbgEnabled, true);
4503 setDebuggerVar(&mDbgAutoShow, true);
4504 setDebuggerVar(&mDbgAutoShowCommandLine, true);
4505 setDebuggerVar(&mDbgAutoShowStatistics, true);
4506 mStartPaused = true;
4507 }
4508 else if (!::strcmp (arg, "--debug-command-line"))
4509 {
4510 setDebuggerVar(&mDbgEnabled, true);
4511 setDebuggerVar(&mDbgAutoShow, true);
4512 setDebuggerVar(&mDbgAutoShowCommandLine, true);
4513 mStartPaused = true;
4514 }
4515 else if (!::strcmp (arg, "--debug-statistics"))
4516 {
4517 setDebuggerVar(&mDbgEnabled, true);
4518 setDebuggerVar(&mDbgAutoShow, true);
4519 setDebuggerVar(&mDbgAutoShowStatistics, true);
4520 mStartPaused = true;
4521 }
4522 else if (!::strcmp (arg, "-no-debug") || !::strcmp (arg, "--no-debug"))
4523 {
4524 setDebuggerVar(&mDbgEnabled, false);
4525 setDebuggerVar(&mDbgAutoShow, false);
4526 setDebuggerVar(&mDbgAutoShowCommandLine, false);
4527 setDebuggerVar(&mDbgAutoShowStatistics, false);
4528 }
4529 /* Not quite debug options, but they're only useful with the debugger bits. */
4530 else if (!::strcmp (arg, "--start-paused"))
4531 mStartPaused = true;
4532 else if (!::strcmp (arg, "--start-running"))
4533 mStartPaused = false;
4534#endif
4535 /** @todo add an else { msgbox(syntax error); exit(1); } here, pretty please... */
4536 i++;
4537 }
4538
4539 if (startVM)
4540 {
4541 QUuid uuid = QUuid(vmNameOrUuid);
4542 if (!uuid.isNull())
4543 {
4544 vmUuid = vmNameOrUuid;
4545 }
4546 else
4547 {
4548 CMachine m = mVBox.FindMachine (vmNameOrUuid);
4549 if (m.isNull())
4550 {
4551 if (showStartVMErrors())
4552 msgCenter().cannotFindMachineByName (mVBox, vmNameOrUuid);
4553 return;
4554 }
4555 vmUuid = m.GetId();
4556 }
4557 }
4558
4559 if (mSettingsPwSet)
4560 mVBox.SetSettingsSecret(mSettingsPw);
4561
4562 if (bForceSeamless && !vmUuid.isEmpty())
4563 {
4564 mVBox.FindMachine(vmUuid).SetExtraData(GUI_Seamless, "on");
4565 }
4566 else if (bForceFullscreen && !vmUuid.isEmpty())
4567 {
4568 mVBox.FindMachine(vmUuid).SetExtraData(GUI_Fullscreen, "on");
4569 }
4570
4571 vm_render_mode = vboxGetRenderMode (vm_render_mode_str);
4572
4573#ifdef VBOX_WITH_DEBUGGER_GUI
4574 /* setup the debugger gui. */
4575 if (RTEnvExist("VBOX_GUI_NO_DEBUGGER"))
4576 mDbgEnabled = mDbgAutoShow = mDbgAutoShowCommandLine = mDbgAutoShowStatistics = false;
4577 if (mDbgEnabled)
4578 {
4579 RTERRINFOSTATIC ErrInfo;
4580 RTErrInfoInitStatic(&ErrInfo);
4581 int vrc = SUPR3HardenedLdrLoadAppPriv("VBoxDbg", &mhVBoxDbg, RTLDRLOAD_FLAGS_LOCAL, &ErrInfo.Core);
4582 if (RT_FAILURE(vrc))
4583 {
4584 mhVBoxDbg = NIL_RTLDRMOD;
4585 mDbgAutoShow = mDbgAutoShowCommandLine = mDbgAutoShowStatistics = false;
4586 LogRel(("Failed to load VBoxDbg, rc=%Rrc - %s\n", vrc, ErrInfo.Core.pszMsg));
4587 }
4588 }
4589#endif
4590
4591 mValid = true;
4592
4593 UIConverter::prepare();
4594
4595 /* Cache IMedium data.
4596 * There could be no used mediums at all,
4597 * but this method should be run anyway just to enumerate null UIMedium object,
4598 * used by some VBox smart widgets, like VBoxMediaComboBox: */
4599 vboxGlobal().startEnumeratingMedia();
4600
4601 /* Prepare global settings change handler: */
4602 connect(&settings(), SIGNAL(propertyChanged(const char*, const char*)),
4603 this, SLOT(sltProcessGlobalSettingChange()));
4604 /* Handle global settings change for the first time: */
4605 sltProcessGlobalSettingChange();
4606
4607 /* Create action pool: */
4608 if (isVMConsoleProcess())
4609 UIActionPoolRuntime::create();
4610 else
4611 UIActionPoolSelector::create();
4612
4613 /* Create network manager: */
4614 UINetworkManager::create();
4615
4616 /* Schedule update manager: */
4617 UIUpdateManager::schedule();
4618}
4619
4620
4621/** @internal
4622 *
4623 * This method should be never called directly. It is called automatically
4624 * when the application terminates.
4625 */
4626void VBoxGlobal::cleanup()
4627{
4628 /* Shutdown update manager: */
4629 UIUpdateManager::shutdown();
4630
4631 /* Destroy network manager: */
4632 UINetworkManager::destroy();
4633
4634 /* Destroy action pool: */
4635 if (isVMConsoleProcess())
4636 UIActionPoolRuntime::destroy();
4637 else
4638 UIActionPoolSelector::destroy();
4639
4640 /* sanity check */
4641 if (!sVBoxGlobalInCleanup)
4642 {
4643 AssertMsgFailed (("Should never be called directly\n"));
4644 return;
4645 }
4646
4647#ifdef VBOX_GUI_WITH_SYSTRAY
4648 if (mIncreasedWindowCounter)
4649 {
4650 /* Decrease open Fe/Qt4 windows reference count. */
4651 int c = mVBox.GetExtraData (GUI_MainWindowCount).toInt() - 1;
4652 AssertMsg ((c >= 0) || (mVBox.isOk()),
4653 ("Something went wrong with the window reference count!"));
4654 if (c < 0)
4655 c = 0; /* Clean up the mess. */
4656 mVBox.SetExtraData (GUI_MainWindowCount,
4657 (c > 0) ? QString ("%1").arg (c) : NULL);
4658 AssertWrapperOk (mVBox);
4659 if (c == 0)
4660 {
4661 mVBox.SetExtraData (GUI_TrayIconWinID, NULL);
4662 AssertWrapperOk (mVBox);
4663 }
4664 }
4665#endif
4666
4667#ifdef VBOX_GUI_WITH_PIDFILE
4668 deletePidfile();
4669#endif
4670
4671 /* Destroy our event handlers */
4672 UIExtraDataEventHandler::destroy();
4673
4674 /* Cleanup medium enumeration thread: */
4675 if (mMediaEnumThread)
4676 {
4677 /* sVBoxGlobalInCleanup is true here, so just wait for the thread */
4678 mMediaEnumThread->wait();
4679 delete mMediaEnumThread;
4680 mMediaEnumThread = 0;
4681 }
4682
4683#ifdef VBOX_WITH_REGISTRATION
4684 if (mRegDlg)
4685 mRegDlg->close();
4686#endif
4687
4688 if (mSelectorWnd)
4689 delete mSelectorWnd;
4690 if (m_pVirtualMachine)
4691 delete m_pVirtualMachine;
4692
4693 UIConverter::cleanup();
4694
4695 /* ensure CGuestOSType objects are no longer used */
4696 mFamilyIDs.clear();
4697 mTypes.clear();
4698
4699 /* media list contains a lot of CUUnknown, release them */
4700 mMediaList.clear();
4701 /* the last steps to ensure we don't use COM any more */
4702 mHost.detach();
4703 mVBox.detach();
4704
4705 /* There may be VBoxMediaEnumEvent instances still in the message
4706 * queue which reference COM objects. Remove them to release those objects
4707 * before uninitializing the COM subsystem. */
4708 QApplication::removePostedEvents (this);
4709
4710 COMBase::CleanupCOM();
4711
4712 mValid = false;
4713}
4714
4715#ifdef VBOX_WITH_DEBUGGER_GUI
4716
4717# define VBOXGLOBAL_DBG_CFG_VAR_FALSE (0)
4718# define VBOXGLOBAL_DBG_CFG_VAR_TRUE (1)
4719# define VBOXGLOBAL_DBG_CFG_VAR_MASK (1)
4720# define VBOXGLOBAL_DBG_CFG_VAR_CMD_LINE RT_BIT(3)
4721# define VBOXGLOBAL_DBG_CFG_VAR_DONE RT_BIT(4)
4722
4723/**
4724 * Initialize a debugger config variable.
4725 *
4726 * @param piDbgCfgVar The debugger config variable to init.
4727 * @param pszEnvVar The environment variable name relating to this
4728 * variable.
4729 * @param pszExtraDataName The extra data name relating to this variable.
4730 * @param fDefault The default value.
4731 */
4732void VBoxGlobal::initDebuggerVar(int *piDbgCfgVar, const char *pszEnvVar, const char *pszExtraDataName, bool fDefault)
4733{
4734 QString strEnvValue;
4735 char szEnvValue[256];
4736 int rc = RTEnvGetEx(RTENV_DEFAULT, pszEnvVar, szEnvValue, sizeof(szEnvValue), NULL);
4737 if (RT_SUCCESS(rc))
4738 {
4739 strEnvValue = QString::fromUtf8(&szEnvValue[0]).toLower().trimmed();
4740 if (strEnvValue.isEmpty())
4741 strEnvValue = "yes";
4742 }
4743 else if (rc != VERR_ENV_VAR_NOT_FOUND)
4744 strEnvValue = "veto";
4745
4746 QString strExtraValue = mVBox.GetExtraData(pszExtraDataName).toLower().trimmed();
4747 if (strExtraValue.isEmpty())
4748 strExtraValue = QString();
4749
4750 if ( strEnvValue.contains("veto") || strExtraValue.contains("veto"))
4751 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4752 else if (strEnvValue.isNull() && strExtraValue.isNull())
4753 *piDbgCfgVar = fDefault ? VBOXGLOBAL_DBG_CFG_VAR_TRUE : VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4754 else
4755 {
4756 QString *pStr = !strEnvValue.isEmpty() ? &strEnvValue : &strExtraValue;
4757 if ( pStr->startsWith("y") // yes
4758 || pStr->startsWith("e") // enabled
4759 || pStr->startsWith("t") // true
4760 || pStr->startsWith("on")
4761 || pStr->toLongLong() != 0)
4762 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_TRUE;
4763 else if ( pStr->startsWith("n") // o
4764 || pStr->startsWith("d") // disable
4765 || pStr->startsWith("f") // false
4766 || pStr->startsWith("off")
4767 || pStr->contains("veto")
4768 || pStr->toLongLong() == 0)
4769 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4770 else
4771 {
4772 LogFunc(("Ignoring unknown value '%s' for '%s'\n", pStr->toAscii().constData(), pStr == &strEnvValue ? pszEnvVar : pszExtraDataName));
4773 *piDbgCfgVar = fDefault ? VBOXGLOBAL_DBG_CFG_VAR_TRUE : VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4774 }
4775 }
4776}
4777
4778/**
4779 * Set a debugger config variable according according to start up argument.
4780 *
4781 * @param piDbgCfgVar The debugger config variable to set.
4782 * @param fState The value from the command line.
4783 */
4784void VBoxGlobal::setDebuggerVar(int *piDbgCfgVar, bool fState)
4785{
4786 if (!(*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_DONE))
4787 *piDbgCfgVar = (fState ? VBOXGLOBAL_DBG_CFG_VAR_TRUE : VBOXGLOBAL_DBG_CFG_VAR_FALSE)
4788 | VBOXGLOBAL_DBG_CFG_VAR_CMD_LINE;
4789}
4790
4791/**
4792 * Checks the state of a debugger config variable, updating it with the machine
4793 * settings on the first invocation.
4794 *
4795 * @returns true / false.
4796 * @param piDbgCfgVar The debugger config variable to consult.
4797 * @param rMachine Reference to the machine object.
4798 * @param pszExtraDataName The extra data name relating to this variable.
4799 */
4800bool VBoxGlobal::isDebuggerWorker(int *piDbgCfgVar, CMachine &rMachine, const char *pszExtraDataName)
4801{
4802 if (!(*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_DONE) && !rMachine.isNull())
4803 {
4804 QString str = mVBox.GetExtraData(pszExtraDataName).toLower().trimmed();
4805 if (str.contains("veto"))
4806 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4807 else if (str.isEmpty() || (*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_CMD_LINE))
4808 *piDbgCfgVar |= VBOXGLOBAL_DBG_CFG_VAR_DONE;
4809 else if ( str.startsWith("y") // yes
4810 || str.startsWith("e") // enabled
4811 || str.startsWith("t") // true
4812 || str.startsWith("on")
4813 || str.toLongLong() != 0)
4814 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_TRUE;
4815 else if ( str.startsWith("n") // no
4816 || str.startsWith("d") // disable
4817 || str.startsWith("f") // false
4818 || str.toLongLong() == 0)
4819 *piDbgCfgVar = VBOXGLOBAL_DBG_CFG_VAR_DONE | VBOXGLOBAL_DBG_CFG_VAR_FALSE;
4820 else
4821 *piDbgCfgVar |= VBOXGLOBAL_DBG_CFG_VAR_DONE;
4822 }
4823
4824 return (*piDbgCfgVar & VBOXGLOBAL_DBG_CFG_VAR_MASK) == VBOXGLOBAL_DBG_CFG_VAR_TRUE;
4825}
4826
4827#endif /* VBOX_WITH_DEBUGGER_GUI */
4828
4829/** @fn vboxGlobal
4830 *
4831 * Shortcut to the static VBoxGlobal::instance() method, for convenience.
4832 */
4833
4834bool VBoxGlobal::switchToMachine(CMachine &machine)
4835{
4836#ifdef Q_WS_MAC
4837 ULONG64 id = machine.ShowConsoleWindow();
4838#else
4839 WId id = (WId) machine.ShowConsoleWindow();
4840#endif
4841 AssertWrapperOk(machine);
4842 if (!machine.isOk())
4843 return false;
4844
4845 /* winId = 0 it means the console window has already done everything
4846 * necessary to implement the "show window" semantics. */
4847 if (id == 0)
4848 return true;
4849
4850#if defined (Q_WS_WIN32) || defined (Q_WS_X11)
4851
4852 return vboxGlobal().activateWindow(id, true);
4853
4854#elif defined (Q_WS_MAC)
4855 /*
4856 * This is just for the case were the other process cannot steal
4857 * the focus from us. It will send us a PSN so we can try.
4858 */
4859 ProcessSerialNumber psn;
4860 psn.highLongOfPSN = id >> 32;
4861 psn.lowLongOfPSN = (UInt32)id;
4862 OSErr rc = ::SetFrontProcess(&psn);
4863 if (!rc)
4864 Log(("GUI: %#RX64 couldn't do SetFrontProcess on itself, the selector (we) had to do it...\n", id));
4865 else
4866 Log(("GUI: Failed to bring %#RX64 to front. rc=%#x\n", id, rc));
4867 return !rc;
4868
4869#endif
4870
4871 return false;
4872
4873 /// @todo Below is the old method of switching to the console window
4874 // based on the process ID of the console process. It should go away
4875 // after the new (callback-based) method is fully tested.
4876#if 0
4877
4878 if (!canSwitchTo())
4879 return false;
4880
4881#if defined (Q_WS_WIN32)
4882
4883 HWND hwnd = mWinId;
4884
4885 /* if there are blockers (modal and modeless dialogs, etc), find the
4886 * topmost one */
4887 HWND hwndAbove = NULL;
4888 do
4889 {
4890 hwndAbove = GetNextWindow(hwnd, GW_HWNDPREV);
4891 HWND hwndOwner;
4892 if (hwndAbove != NULL &&
4893 ((hwndOwner = GetWindow(hwndAbove, GW_OWNER)) == hwnd ||
4894 hwndOwner == hwndAbove))
4895 hwnd = hwndAbove;
4896 else
4897 break;
4898 }
4899 while (1);
4900
4901 /* first, check that the primary window is visible */
4902 if (IsIconic(mWinId))
4903 ShowWindow(mWinId, SW_RESTORE);
4904 else if (!IsWindowVisible(mWinId))
4905 ShowWindow(mWinId, SW_SHOW);
4906
4907#if 0
4908 LogFlowFunc(("mWinId=%08X hwnd=%08X\n", mWinId, hwnd));
4909#endif
4910
4911 /* then, activate the topmost in the group */
4912 AllowSetForegroundWindow(m_pid);
4913 SetForegroundWindow(hwnd);
4914
4915 return true;
4916
4917#elif defined (Q_WS_X11)
4918
4919 return false;
4920
4921#elif defined (Q_WS_MAC)
4922
4923 ProcessSerialNumber psn;
4924 OSStatus rc = ::GetProcessForPID(m_pid, &psn);
4925 if (!rc)
4926 {
4927 rc = ::SetFrontProcess(&psn);
4928
4929 if (!rc)
4930 {
4931 ShowHideProcess(&psn, true);
4932 return true;
4933 }
4934 }
4935 return false;
4936
4937#else
4938
4939 return false;
4940
4941#endif
4942
4943#endif
4944}
4945
4946bool VBoxGlobal::launchMachine(CMachine &machine, bool fHeadless /* = false */)
4947{
4948 if (machine.CanShowConsoleWindow())
4949 return VBoxGlobal::switchToMachine(machine);
4950
4951 KMachineState state = machine.GetState(); NOREF(state);
4952 AssertMsg( state == KMachineState_PoweredOff
4953 || state == KMachineState_Saved
4954 || state == KMachineState_Teleported
4955 || state == KMachineState_Aborted
4956 , ("Machine must be PoweredOff/Saved/Aborted (%d)", state));
4957
4958 CVirtualBox vbox = vboxGlobal().virtualBox();
4959 CSession session;
4960 session.createInstance(CLSID_Session);
4961 if (session.isNull())
4962 {
4963 msgCenter().cannotOpenSession(session);
4964 return false;
4965 }
4966
4967#if defined(Q_OS_WIN32)
4968 /* allow the started VM process to make itself the foreground window */
4969 AllowSetForegroundWindow(ASFW_ANY);
4970#endif
4971
4972 QString env;
4973#if defined(Q_WS_X11)
4974 /* make sure the VM process will start on the same display as the Selector */
4975 const char *display = RTEnvGet("DISPLAY");
4976 if (display)
4977 env.append(QString("DISPLAY=%1\n").arg(display));
4978 const char *xauth = RTEnvGet("XAUTHORITY");
4979 if (xauth)
4980 env.append(QString("XAUTHORITY=%1\n").arg(xauth));
4981#endif
4982 const QString strType = fHeadless ? "headless" : "GUI/Qt";
4983
4984 CProgress progress = machine.LaunchVMProcess(session, strType, env);
4985 if ( !vbox.isOk()
4986 || progress.isNull())
4987 {
4988 msgCenter().cannotOpenSession(vbox, machine);
4989 return false;
4990 }
4991
4992 /* Hide the "VM spawning" progress dialog */
4993 /* I hope 1 minute will be enough to spawn any running VM silently, isn't it? */
4994 int iSpawningDuration = 60000;
4995 msgCenter().showModalProgressDialog(progress, machine.GetName(), "", 0, false, iSpawningDuration);
4996 if (progress.GetResultCode() != 0)
4997 msgCenter().cannotOpenSession(vbox, machine, progress);
4998
4999 session.UnlockMachine();
5000
5001 return true;
5002}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use