PageRenderTime 38ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/src/VBox/Frontends/VirtualBox/src/globals/VBoxGlobal.cpp

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