VirtualBox

source: vbox/trunk/src/VBox/Frontends/VirtualBox4/src/VBoxGlobal.cpp@ 14056

Last change on this file since 14056 was 14056, checked in by vboxsync, 16 years ago

FE/Qt4: Removed some ancient VBOX_GUI_DEBUG stuff.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 177.9 KB
Line 
1/** @file
2 *
3 * VBox frontends: Qt GUI ("VirtualBox"):
4 * VBoxGlobal class implementation
5 */
6
7/*
8 * Copyright (C) 2008 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#include "VBoxGlobal.h"
24#include <VBox/VBoxHDD-new.h>
25
26#include "VBoxDefs.h"
27#include "VBoxSelectorWnd.h"
28#include "VBoxConsoleWnd.h"
29#include "VBoxProblemReporter.h"
30#include "QIHotKeyEdit.h"
31#include "QIMessageBox.h"
32#include "QIDialogButtonBox.h"
33
34#ifdef VBOX_WITH_REGISTRATION
35#include "VBoxRegistrationDlg.h"
36#endif
37#include "VBoxUpdateDlg.h"
38
39/* Qt includes */
40#include <QLibraryInfo>
41#include <QFileDialog>
42#include <QToolTip>
43#include <QTranslator>
44#include <QDesktopWidget>
45#include <QMutex>
46#include <QToolButton>
47#include <QProcess>
48#include <QThread>
49#include <QPainter>
50
51#ifdef Q_WS_X11
52#ifndef VBOX_OSE
53# include "VBoxLicenseViewer.h"
54#endif /* VBOX_OSE */
55
56#include <QTextBrowser>
57#include <QScrollBar>
58#include <QX11Info>
59#endif
60
61
62#if defined (Q_WS_MAC)
63#include "VBoxUtils.h"
64#include <Carbon/Carbon.h> // for HIToolbox/InternetConfig
65#endif
66
67#if defined (Q_WS_WIN)
68#include "shlobj.h"
69#include <QEventLoop>
70#endif
71
72#if defined (Q_WS_X11)
73#undef BOOL /* typedef CARD8 BOOL in Xmd.h conflicts with #define BOOL PRBool
74 * in COMDefs.h. A better fix would be to isolate X11-specific
75 * stuff by placing XX* helpers below to a separate source file. */
76#include <X11/X.h>
77#include <X11/Xmd.h>
78#include <X11/Xlib.h>
79#include <X11/Xatom.h>
80#define BOOL PRBool
81#endif
82
83#include <iprt/asm.h>
84#include <iprt/err.h>
85#include <iprt/param.h>
86#include <iprt/path.h>
87#include <iprt/env.h>
88#include <iprt/file.h>
89#include <iprt/ldr.h>
90
91#if defined (Q_WS_X11)
92#include <iprt/mem.h>
93#endif
94
95//#warning "port me: check this"
96/// @todo bird: Use (U)INT_PTR, (U)LONG_PTR, DWORD_PTR, or (u)intptr_t.
97#if defined(Q_OS_WIN64)
98typedef __int64 Q_LONG; /* word up to 64 bit signed */
99typedef unsigned __int64 Q_ULONG; /* word up to 64 bit unsigned */
100#else
101typedef long Q_LONG; /* word up to 64 bit signed */
102typedef unsigned long Q_ULONG; /* word up to 64 bit unsigned */
103#endif
104
105// VBoxMedium
106/////////////////////////////////////////////////////////////////////////////
107
108void VBoxMedium::init()
109{
110 AssertReturnVoid (!mMedium.isNull());
111
112 switch (mType)
113 {
114 case VBoxDefs::MediaType_HardDisk:
115 {
116 mHardDisk = mMedium;
117 AssertReturnVoid (!mHardDisk.isNull());
118 break;
119 }
120 case VBoxDefs::MediaType_DVD:
121 {
122 mDVDImage = mMedium;
123 AssertReturnVoid (!mDVDImage.isNull());
124 Assert (mParent == NULL);
125 break;
126 }
127 case VBoxDefs::MediaType_Floppy:
128 {
129 mFloppyImage = mMedium;
130 AssertReturnVoid (!mFloppyImage.isNull());
131 Assert (mParent == NULL);
132 break;
133 }
134 default:
135 AssertFailed();
136 }
137
138 refresh();
139}
140
141/**
142 * Queries the medium state. Call this and then read the state field instad
143 * of calling GetState() on medium directly as it will properly handle the
144 * situation when GetState() itself fails by setting state to Inaccessible
145 * and memorizing the error info describing why GetState() failed.
146 *
147 * As the last step, this method calls #refresh() to refresh all precomposed
148 * strings.
149 *
150 * @note This method blocks for the duration of the state check. Since this
151 * check may take quite a while (e.g. for a medium located on a
152 * network share), the calling thread must not be the UI thread. You
153 * have been warned.
154 */
155void VBoxMedium::blockAndQueryState()
156{
157 mState = mMedium.GetState();
158
159 /* save the result to distinguish between inaccessible and e.g.
160 * uninitialized objects */
161 mResult = COMResult (mMedium);
162
163 if (!mResult.isOk())
164 {
165 mState = KMediaState_Inaccessible;
166 mLastAccessError = QString::null;
167 }
168 else
169 mLastAccessError = mMedium.GetLastAccessError();
170
171 refresh();
172}
173
174/**
175 * Refreshes the precomposed strings containing such media parameters as
176 * location, size by querying the respective data from the associated
177 * media object.
178 *
179 * Note that some string such as #size() are meaningless if the media state is
180 * KMediaState_NotCreated (i.e. the medium has not yet been checked for
181 * accessibility).
182 */
183void VBoxMedium::refresh()
184{
185 mId = mMedium.GetId();
186 mLocation = mMedium.GetLocation();
187 mName = mMedium.GetName();
188
189 if (mType == VBoxDefs::MediaType_HardDisk)
190 {
191 /// @todo NEWMEDIA use CSystemProperties::GetHardDIskFormats to see if the
192 /// given hard disk format is a file
193 mLocation = QDir::toNativeSeparators (mLocation);
194 mHardDiskFormat = mHardDisk.GetFormat();
195 mHardDiskType = vboxGlobal().hardDiskTypeString (mHardDisk);
196
197 mIsReadOnly = mHardDisk.GetReadOnly();
198
199 /* adjust the parent if necessary (note that mParent must always point
200 * to an item from VBoxGlobal::currentMediaList()) */
201
202 CHardDisk2 parent = mHardDisk.GetParent();
203 Assert (!parent.isNull() || mParent == NULL);
204
205 if (!parent.isNull() &&
206 (mParent == NULL || mParent->mHardDisk != parent))
207 {
208 /* search for the parent (must be there) */
209 const VBoxMediaList &list = vboxGlobal().currentMediaList();
210 for (VBoxMediaList::const_iterator it = list.begin();
211 it != list.end(); ++ it)
212 {
213 if ((*it).mType != VBoxDefs::MediaType_HardDisk)
214 break;
215
216 if ((*it).mHardDisk == parent)
217 {
218 /* we unconst here because by the const list we don't mean
219 * const items */
220 mParent = unconst (&*it);
221 break;
222 }
223 }
224
225 Assert (mParent != NULL && mParent->mHardDisk == parent);
226 }
227 }
228 else
229 {
230 mLocation = QDir::toNativeSeparators (mLocation);
231 mHardDiskFormat = QString::null;
232 mHardDiskType = QString::null;
233
234 mIsReadOnly = false;
235 }
236
237 if (mState != KMediaState_Inaccessible &&
238 mState != KMediaState_NotCreated)
239 {
240 mSize = vboxGlobal().formatSize (mMedium.GetSize());
241 if (mType == VBoxDefs::MediaType_HardDisk)
242 mLogicalSize = vboxGlobal()
243 .formatSize (mHardDisk.GetLogicalSize() * _1M);
244 else
245 mLogicalSize = mSize;
246 }
247 else
248 {
249 mSize = mLogicalSize = QString ("--");
250 }
251
252 /* detect usage */
253
254 mUsage = QString::null; /* important: null means not used! */
255
256 mCurStateMachineIds.clear();
257
258 QVector <QUuid> machineIds = mMedium.GetMachineIds();
259 if (machineIds.size() > 0)
260 {
261 QString usage;
262
263 CVirtualBox vbox = vboxGlobal().virtualBox();
264
265 for (QVector <QUuid>::ConstIterator it = machineIds.begin();
266 it != machineIds.end(); ++ it)
267 {
268 CMachine machine = vbox.GetMachine (*it);
269
270 QString name = machine.GetName();
271 QString snapshots;
272
273 QVector <QUuid> snapIds = mMedium.GetSnapshotIds (*it);
274 for (QVector <QUuid>::ConstIterator jt = snapIds.begin();
275 jt != snapIds.end(); ++ jt)
276 {
277 if (*jt == *it)
278 {
279 /* the medium is attached to the machine in the current
280 * state, we don't distinguish this for now by always
281 * giving the VM name in front of snapshot names. */
282
283 mCurStateMachineIds.push_back (*jt);
284 continue;
285 }
286
287 CSnapshot snapshot = machine.GetSnapshot (*jt);
288 if (!snapshots.isNull())
289 snapshots += ", ";
290 snapshots += snapshot.GetName();
291 }
292
293 if (!usage.isNull())
294 usage += ", ";
295
296 usage += name;
297
298 if (!snapshots.isNull())
299 {
300 usage += QString (" (%2)").arg (snapshots);
301 mIsUsedInSnapshots = true;
302 }
303 else
304 mIsUsedInSnapshots = false;
305 }
306
307 Assert (!usage.isEmpty());
308 mUsage = usage;
309 }
310
311 /* compose the tooltip (makes sense to keep the format in sync with
312 * VBoxMediaManagerDlg::languageChangeImp() and
313 * VBoxMediaManagerDlg::processCurrentChanged()) */
314
315 mToolTip = QString ("<nobr><b>%1</b></nobr>").arg (mLocation);
316
317 if (mType == VBoxDefs::MediaType_HardDisk)
318 {
319 mToolTip += VBoxGlobal::tr (
320 "<br><nobr>Type&nbsp;(Format):&nbsp;&nbsp;%2&nbsp;(%3)</nobr>",
321 "hard disk")
322 .arg (mHardDiskType)
323 .arg (mHardDiskFormat);
324 }
325
326 mToolTip += VBoxGlobal::tr (
327 "<br><nobr>Attached to:&nbsp;&nbsp;%1</nobr>", "medium")
328 .arg (mUsage.isNull() ?
329 VBoxGlobal::tr ("<i>Not&nbsp;Attached</i>", "medium") :
330 mUsage);
331
332 switch (mState)
333 {
334 case KMediaState_NotCreated:
335 {
336 mToolTip += VBoxGlobal::tr ("<br><i>Checking accessibility...</i>",
337 "medium");
338 break;
339 }
340 case KMediaState_Inaccessible:
341 {
342 if (mResult.isOk())
343 {
344 /* not accessibile */
345 mToolTip += QString ("<hr>%1").
346 arg (VBoxGlobal::highlight (mLastAccessError,
347 true /* aToolTip */));
348 }
349 else
350 {
351 /* accessibility check (eg GetState()) itself failed */
352 mToolTip = VBoxGlobal::tr (
353 "<hr>Failed to check media accessibility.<br>%1.",
354 "medium").
355 arg (VBoxProblemReporter::formatErrorInfo (mResult));
356 }
357 break;
358 }
359 default:
360 break;
361 }
362
363 /* reset mNoDiffs */
364 mNoDiffs.isSet = false;
365}
366
367/**
368 * Returns a root medium of this medium. For non-hard disk media, this is always
369 * this medium itself.
370 */
371VBoxMedium &VBoxMedium::root() const
372{
373 VBoxMedium *root = unconst (this);
374 while (root->mParent != NULL)
375 root = root->mParent;
376
377 return *root;
378}
379
380/**
381 * Returns a tooltip for this medium.
382 *
383 * In "don't show diffs" mode (where the attributes of the base hard disk are
384 * shown instead of the attributes of the differencing hard disk), extra
385 * information will be added to the tooltip to give the user a hint that the
386 * medium is actually a differencing hard disk.
387 *
388 * @param aNoDiffs @c true to enable user-friendly "don't show diffs" mode.
389 * @param aCheckRO @c true to perform the #readOnly() check and add a notice
390 * accordingly.
391 */
392QString VBoxMedium::toolTip (bool aNoDiffs /*= false*/,
393 bool aCheckRO /*= false*/) const
394{
395 unconst (this)->checkNoDiffs (aNoDiffs);
396
397 QString tip = aNoDiffs ? mNoDiffs.toolTip : mToolTip;
398
399 if (aCheckRO && mIsReadOnly)
400 tip += VBoxGlobal::tr (
401 "<hr><img src=%1/>&nbsp;Attaching this hard disk will "
402 "be performed indirectly using a newly created "
403 "differencing hard disk.",
404 "medium").
405 arg (":/new_16px.png");
406
407 return tip;
408}
409
410/**
411 * Returns an icon corresponding to the media state. Distinguishes between
412 * the Inaccessible state and the situation when querying the state itself
413 * failed.
414 *
415 * In "don't show diffs" mode (where the attributes of the base hard disk are
416 * shown instead of the attributes of the differencing hard disk), the most
417 * worst media state on the given hard disk chain will be used to select the
418 * media icon.
419 *
420 * @param aNoDiffs @c true to enable user-friendly "don't show diffs" mode.
421 * @param aCheckRO @c true to perform the #readOnly() check and change the icon
422 * accordingly.
423 */
424QPixmap VBoxMedium::icon (bool aNoDiffs /*= false*/,
425 bool aCheckRO /*= false*/) const
426{
427 QPixmap icon;
428
429 if (state (aNoDiffs) == KMediaState_Inaccessible)
430 icon = result (aNoDiffs).isOk() ?
431 vboxGlobal().warningIcon() : vboxGlobal().errorIcon();
432
433 if (aCheckRO && mIsReadOnly)
434 icon = VBoxGlobal::
435 joinPixmaps (icon, QPixmap (":/new_16px.png"));
436
437 return icon;
438}
439
440/**
441 * Returns the details of this medium as a single-line string
442 *
443 * For hard disks, the details include the location, type and the logical size
444 * of the hard disk. Note that if @a aNoDiffs is @c true, these properties are
445 * queried on the root hard disk of the given hard disk because the primary
446 * purpose of the returned string is to be human readabile (so that seeing a
447 * complex diff hard disk name is usually not desirable).
448 *
449 * For other media types, the location and the actual size are returned.
450 * Arguments @a aPredictDiff and @a aNoRoot are ignored in this case.
451 *
452 * @param aNoDiffs @c true to enable user-friendly "don't show diffs" mode.
453 * @param aPredictDiff @c true to mark the hard disk as differencing if
454 * attaching it would create a differencing hard disk (not
455 * used when @a aNoRoot is true).
456 * @param aUseHTML @c true to allow for emphasizing using bold and italics.
457 *
458 * @note Use #detailsHTML() instead of passing @c true for @a aUseHTML.
459 *
460 * @note The media object may become uninitialized by a third party while this
461 * method is reading its properties. In this case, the method will return
462 * an empty string.
463 */
464QString VBoxMedium::details (bool aNoDiffs /*= false*/,
465 bool aPredictDiff /*= false*/,
466 bool aUseHTML /*= false */) const
467{
468 // @todo *** the below check is rough; if mMedium becomes uninitialized, any
469 // of getters called afterwards will also fail. The same relates to the
470 // root hard disk object (that will be the hard disk itself in case of
471 // non-differencing disks). However, this check was added to fix a
472 // particular use case: when the hard disk is a differencing hard disk and
473 // it happens to be discarded (and uninitialized) after this method is
474 // called but before we read all its properties (yes, it's possible!), the
475 // root object will be null and calling methods on it will assert in the
476 // debug builds. This check seems to be enough as a quick solution (fresh
477 // hard disk attachments will be re-read by a machine state change signal
478 // after the discard operation is finished, so the user will eventually see
479 // correct data), but in order to solve the problem properly we need to use
480 // exceptions everywhere (or check the result after every method call). See
481 // also Defect #2149.
482 if (!mMedium.isOk())
483 return QString::null;
484
485 QString details, str;
486
487 VBoxMedium *root = unconst (this);
488 KMediaState state = mState;
489
490 if (mType == VBoxDefs::MediaType_HardDisk)
491 {
492 if (aNoDiffs)
493 {
494 root = &this->root();
495
496 bool isDiff =
497 (!aPredictDiff && mParent != NULL) ||
498 (aPredictDiff && mIsReadOnly);
499
500 details = isDiff && aUseHTML ?
501 QString ("<i>%1</i>, ").arg (root->mHardDiskType) :
502 QString ("%1, ").arg (root->mHardDiskType);
503
504 /* overall (worst) state */
505 state = this->state (true /* aNoDiffs */);
506
507 /* we cannot get the logical size if the root is not checked yet */
508 if (root->mState == KMediaState_NotCreated)
509 state = KMediaState_NotCreated;
510 }
511 else
512 {
513 details = QString ("%1, ").arg (root->mHardDiskType);
514 }
515 }
516
517 /// @todo prepend the details with the warning/error
518 // icon when not accessible
519
520 switch (state)
521 {
522 case KMediaState_NotCreated:
523 str = VBoxGlobal::tr ("Checking...", "medium");
524 details += aUseHTML ? QString ("<i>%1</i>").arg (str) : str;
525 break;
526 case KMediaState_Inaccessible:
527 str = VBoxGlobal::tr ("Inaccessible", "medium");
528 details += aUseHTML ? QString ("<b>%1</b>").arg (str) : str;
529 break;
530 default:
531 details += mType == VBoxDefs::MediaType_HardDisk ?
532 root->mLogicalSize : root->mSize;
533 break;
534 }
535
536 details = aUseHTML ?
537 QString ("%1 (<nobr>%2</nobr>)").
538 arg (VBoxGlobal::locationForHTML (root->mName), details) :
539 QString ("%1 (%2)").
540 arg (VBoxGlobal::locationForHTML (root->mName), details);
541
542 return details;
543}
544
545/**
546 * Checks if mNoDiffs is filled in and does it if not.
547 *
548 * @param aNoDiffs @if false, this method immediately returns.
549 */
550void VBoxMedium::checkNoDiffs (bool aNoDiffs)
551{
552 if (!aNoDiffs || mNoDiffs.isSet)
553 return;
554
555 /* fill mNoDiffs */
556
557 mNoDiffs.toolTip = QString::null;
558
559 /* detect the overall (worst) state of the given hard disk chain */
560 mNoDiffs.state = mState;
561 for (VBoxMedium *cur = mParent; cur != NULL;
562 cur = cur->mParent)
563 {
564 if (cur->mState == KMediaState_Inaccessible)
565 {
566 mNoDiffs.state = cur->mState;
567
568 if (mNoDiffs.toolTip.isNull())
569 mNoDiffs.toolTip = VBoxGlobal::tr (
570 "<hr>Some of the media in this hard disk chain are "
571 "inaccessible. Please use the Virtual Media Manager "
572 "in <b>Show Differencing Hard Disks</b> mode to inspect "
573 "these media.");
574
575 if (!cur->mResult.isOk())
576 {
577 mNoDiffs.result = cur->mResult;
578 break;
579 }
580
581 /* comtinue looking for another !cur->mResult.isOk() */
582 }
583 }
584
585 if (mParent != NULL && !mIsReadOnly)
586 {
587 mNoDiffs.toolTip = VBoxGlobal::tr (
588 "%1"
589 "<hr>This base hard disk is indirectly attached using the "
590 "following differencing hard disk:<br>"
591 "%2%3").
592 arg (root().toolTip(), mToolTip, mNoDiffs.toolTip);
593 }
594
595 if (mNoDiffs.toolTip.isNull())
596 mNoDiffs.toolTip = mToolTip;
597
598 mNoDiffs.isSet = true;
599}
600
601// VBoxMediaEnumEvent
602/////////////////////////////////////////////////////////////////////////////
603
604class VBoxMediaEnumEvent : public QEvent
605{
606public:
607
608 /** Constructs a regular enum event */
609 VBoxMediaEnumEvent (const VBoxMedium &aMedium)
610 : QEvent ((QEvent::Type) VBoxDefs::MediaEnumEventType)
611 , mMedium (aMedium), mLast (false)
612 {}
613 /** Constructs the last enum event */
614 VBoxMediaEnumEvent()
615 : QEvent ((QEvent::Type) VBoxDefs::MediaEnumEventType)
616 , mLast (true)
617 {}
618
619 /** The last enumerated medium (not valid when #last is true) */
620 const VBoxMedium mMedium;
621 /** Whether this is the last event for the given enumeration or not */
622 const bool mLast;
623};
624
625#if defined (Q_WS_WIN)
626class VBoxShellExecuteEvent : public QEvent
627{
628public:
629
630 /** Constructs a regular enum event */
631 VBoxShellExecuteEvent (QThread *aThread, const QString &aURL,
632 bool aOk)
633 : QEvent ((QEvent::Type) VBoxDefs::ShellExecuteEventType)
634 , mThread (aThread), mURL (aURL), mOk (aOk)
635 {}
636
637 QThread *mThread;
638 QString mURL;
639 bool mOk;
640};
641#endif
642
643// VirtualBox callback class
644/////////////////////////////////////////////////////////////////////////////
645
646class VBoxCallback : public IVirtualBoxCallback
647{
648public:
649
650 VBoxCallback (VBoxGlobal &aGlobal)
651 : mGlobal (aGlobal)
652 , mIsRegDlgOwner (false), mIsUpdDlgOwner (false)
653 {
654#if defined (Q_OS_WIN32)
655 refcnt = 0;
656#endif
657 }
658
659 virtual ~VBoxCallback() {}
660
661 NS_DECL_ISUPPORTS
662
663#if defined (Q_OS_WIN32)
664 STDMETHOD_(ULONG, AddRef)()
665 {
666 return ::InterlockedIncrement (&refcnt);
667 }
668 STDMETHOD_(ULONG, Release)()
669 {
670 long cnt = ::InterlockedDecrement (&refcnt);
671 if (cnt == 0)
672 delete this;
673 return cnt;
674 }
675 STDMETHOD(QueryInterface) (REFIID riid , void **ppObj)
676 {
677 if (riid == IID_IUnknown) {
678 *ppObj = this;
679 AddRef();
680 return S_OK;
681 }
682 if (riid == IID_IVirtualBoxCallback) {
683 *ppObj = this;
684 AddRef();
685 return S_OK;
686 }
687 *ppObj = NULL;
688 return E_NOINTERFACE;
689 }
690#endif
691
692 // IVirtualBoxCallback methods
693
694 // Note: we need to post custom events to the GUI event queue
695 // instead of doing what we need directly from here because on Win32
696 // these callback methods are never called on the main GUI thread.
697 // Another reason to handle events asynchronously is that internally
698 // most callback interface methods are called from under the initiator
699 // object's lock, so accessing the initiator object (for example, reading
700 // some property) directly from the callback method will definitely cause
701 // a deadlock.
702
703 STDMETHOD(OnMachineStateChange) (IN_GUIDPARAM id, MachineState_T state)
704 {
705 postEvent (new VBoxMachineStateChangeEvent (COMBase::ToQUuid (id),
706 (KMachineState) state));
707 return S_OK;
708 }
709
710 STDMETHOD(OnMachineDataChange) (IN_GUIDPARAM id)
711 {
712 postEvent (new VBoxMachineDataChangeEvent (COMBase::ToQUuid (id)));
713 return S_OK;
714 }
715
716 STDMETHOD(OnExtraDataCanChange)(IN_GUIDPARAM id,
717 IN_BSTRPARAM key, IN_BSTRPARAM value,
718 BSTR *error, BOOL *allowChange)
719 {
720 if (!error || !allowChange)
721 return E_INVALIDARG;
722
723 if (COMBase::ToQUuid (id).isNull())
724 {
725 /* it's a global extra data key someone wants to change */
726 QString sKey = QString::fromUtf16 (key);
727 QString sVal = QString::fromUtf16 (value);
728 if (sKey.startsWith ("GUI/"))
729 {
730 if (sKey == VBoxDefs::GUI_RegistrationDlgWinID)
731 {
732 if (mIsRegDlgOwner)
733 {
734 if (sVal.isEmpty() ||
735 sVal == QString ("%1")
736 .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
737 *allowChange = TRUE;
738 else
739 *allowChange = FALSE;
740 }
741 else
742 *allowChange = TRUE;
743 return S_OK;
744 }
745
746 if (sKey == VBoxDefs::GUI_UpdateDlgWinID)
747 {
748 if (mIsUpdDlgOwner)
749 {
750 if (sVal.isEmpty() ||
751 sVal == QString ("%1")
752 .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
753 *allowChange = TRUE;
754 else
755 *allowChange = FALSE;
756 }
757 else
758 *allowChange = TRUE;
759 return S_OK;
760 }
761
762 /* try to set the global setting to check its syntax */
763 VBoxGlobalSettings gs (false /* non-null */);
764 if (gs.setPublicProperty (sKey, sVal))
765 {
766 /* this is a known GUI property key */
767 if (!gs)
768 {
769 /* disallow the change when there is an error*/
770 *error = SysAllocString ((const OLECHAR *)
771 (gs.lastError().isNull() ? 0 : gs.lastError().utf16()));
772 *allowChange = FALSE;
773 }
774 else
775 *allowChange = TRUE;
776 return S_OK;
777 }
778 }
779 }
780
781 /* not interested in this key -- never disagree */
782 *allowChange = TRUE;
783 return S_OK;
784 }
785
786 STDMETHOD(OnExtraDataChange) (IN_GUIDPARAM id,
787 IN_BSTRPARAM key, IN_BSTRPARAM value)
788 {
789 if (COMBase::ToQUuid (id).isNull())
790 {
791 QString sKey = QString::fromUtf16 (key);
792 QString sVal = QString::fromUtf16 (value);
793 if (sKey.startsWith ("GUI/"))
794 {
795 if (sKey == VBoxDefs::GUI_RegistrationDlgWinID)
796 {
797 if (sVal.isEmpty())
798 {
799 mIsRegDlgOwner = false;
800 QApplication::postEvent (&mGlobal, new VBoxCanShowRegDlgEvent (true));
801 }
802 else if (sVal == QString ("%1")
803 .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
804 {
805 mIsRegDlgOwner = true;
806 QApplication::postEvent (&mGlobal, new VBoxCanShowRegDlgEvent (true));
807 }
808 else
809 QApplication::postEvent (&mGlobal, new VBoxCanShowRegDlgEvent (false));
810 }
811 if (sKey == VBoxDefs::GUI_UpdateDlgWinID)
812 {
813 if (sVal.isEmpty())
814 {
815 mIsUpdDlgOwner = false;
816 QApplication::postEvent (&mGlobal, new VBoxCanShowUpdDlgEvent (true));
817 }
818 else if (sVal == QString ("%1")
819 .arg ((qulonglong) vboxGlobal().mainWindow()->winId()))
820 {
821 mIsUpdDlgOwner = true;
822 QApplication::postEvent (&mGlobal, new VBoxCanShowUpdDlgEvent (true));
823 }
824 else
825 QApplication::postEvent (&mGlobal, new VBoxCanShowUpdDlgEvent (false));
826 }
827 if (sKey == "GUI/LanguageID")
828 QApplication::postEvent (&mGlobal, new VBoxChangeGUILanguageEvent (sVal));
829
830 mMutex.lock();
831 mGlobal.gset.setPublicProperty (sKey, sVal);
832 mMutex.unlock();
833 Assert (!!mGlobal.gset);
834 }
835 }
836 return S_OK;
837 }
838
839 STDMETHOD(OnMediaRegistered) (IN_GUIDPARAM id, DeviceType_T type,
840 BOOL registered)
841 {
842 /** @todo */
843 Q_UNUSED (id);
844 Q_UNUSED (type);
845 Q_UNUSED (registered);
846 return S_OK;
847 }
848
849 STDMETHOD(OnMachineRegistered) (IN_GUIDPARAM id, BOOL registered)
850 {
851 postEvent (new VBoxMachineRegisteredEvent (COMBase::ToQUuid (id),
852 registered));
853 return S_OK;
854 }
855
856 STDMETHOD(OnSessionStateChange) (IN_GUIDPARAM id, SessionState_T state)
857 {
858 postEvent (new VBoxSessionStateChangeEvent (COMBase::ToQUuid (id),
859 (KSessionState) state));
860 return S_OK;
861 }
862
863 STDMETHOD(OnSnapshotTaken) (IN_GUIDPARAM aMachineId, IN_GUIDPARAM aSnapshotId)
864 {
865 postEvent (new VBoxSnapshotEvent (COMBase::ToQUuid (aMachineId),
866 COMBase::ToQUuid (aSnapshotId),
867 VBoxSnapshotEvent::Taken));
868 return S_OK;
869 }
870
871 STDMETHOD(OnSnapshotDiscarded) (IN_GUIDPARAM aMachineId, IN_GUIDPARAM aSnapshotId)
872 {
873 postEvent (new VBoxSnapshotEvent (COMBase::ToQUuid (aMachineId),
874 COMBase::ToQUuid (aSnapshotId),
875 VBoxSnapshotEvent::Discarded));
876 return S_OK;
877 }
878
879 STDMETHOD(OnSnapshotChange) (IN_GUIDPARAM aMachineId, IN_GUIDPARAM aSnapshotId)
880 {
881 postEvent (new VBoxSnapshotEvent (COMBase::ToQUuid (aMachineId),
882 COMBase::ToQUuid (aSnapshotId),
883 VBoxSnapshotEvent::Changed));
884 return S_OK;
885 }
886
887 STDMETHOD(OnGuestPropertyChange) (IN_GUIDPARAM /* id */,
888 IN_BSTRPARAM /* key */,
889 IN_BSTRPARAM /* value */,
890 IN_BSTRPARAM /* flags */)
891 {
892 return S_OK;
893 }
894
895private:
896
897 void postEvent (QEvent *e)
898 {
899 // currently, we don't post events if we are in the VM execution
900 // console mode, to save some CPU ticks (so far, there was no need
901 // to handle VirtualBox callback events in the execution console mode)
902
903 if (!mGlobal.isVMConsoleProcess())
904 QApplication::postEvent (&mGlobal, e);
905 }
906
907 VBoxGlobal &mGlobal;
908
909 /** protects #OnExtraDataChange() */
910 QMutex mMutex;
911
912 bool mIsRegDlgOwner;
913 bool mIsUpdDlgOwner;
914
915#if defined (Q_OS_WIN32)
916private:
917 long refcnt;
918#endif
919};
920
921#if !defined (Q_OS_WIN32)
922NS_DECL_CLASSINFO (VBoxCallback)
923NS_IMPL_THREADSAFE_ISUPPORTS1_CI (VBoxCallback, IVirtualBoxCallback)
924#endif
925
926// Helpers for VBoxGlobal::getOpenFileName() & getExistingDirectory()
927/////////////////////////////////////////////////////////////////////////////
928
929#if defined Q_WS_WIN
930
931extern void qt_enter_modal (QWidget*);
932extern void qt_leave_modal (QWidget*);
933
934static QString extractFilter (const QString &aRawFilter)
935{
936 static const char qt_file_dialog_filter_reg_exp[] =
937 "([a-zA-Z0-9 ]*)\\(([a-zA-Z0-9_.*? +;#\\[\\]]*)\\)$";
938
939 QString result = aRawFilter;
940 QRegExp r (QString::fromLatin1 (qt_file_dialog_filter_reg_exp));
941 int index = r.indexIn (result);
942 if (index >= 0)
943 result = r.cap (2);
944 return result.replace (QChar (' '), QChar (';'));
945}
946
947/**
948 * Converts QFileDialog filter list to Win32 API filter list.
949 */
950static QString winFilter (const QString &aFilter)
951{
952 QStringList filterLst;
953
954 if (!aFilter.isEmpty())
955 {
956 int i = aFilter.indexOf (";;", 0);
957 QString sep (";;");
958 if (i == -1)
959 {
960 if (aFilter.indexOf ("\n", 0) != -1)
961 {
962 sep = "\n";
963 i = aFilter.indexOf (sep, 0);
964 }
965 }
966
967 filterLst = aFilter.split (sep);
968 }
969
970 QStringList::Iterator it = filterLst.begin();
971 QString winfilters;
972 for (; it != filterLst.end(); ++it)
973 {
974 winfilters += *it;
975 winfilters += QChar::Null;
976 winfilters += extractFilter (*it);
977 winfilters += QChar::Null;
978 }
979 winfilters += QChar::Null;
980 return winfilters;
981}
982
983/*
984 * Callback function to control the native Win32 API file dialog
985 */
986UINT_PTR CALLBACK OFNHookProc (HWND aHdlg, UINT aUiMsg, WPARAM aWParam, LPARAM aLParam)
987{
988 if (aUiMsg == WM_NOTIFY)
989 {
990 OFNOTIFY *notif = (OFNOTIFY*) aLParam;
991 if (notif->hdr.code == CDN_TYPECHANGE)
992 {
993 /* locate native dialog controls */
994 HWND parent = GetParent (aHdlg);
995 HWND button = GetDlgItem (parent, IDOK);
996 HWND textfield = ::GetDlgItem (parent, cmb13);
997 if (textfield == NULL)
998 textfield = ::GetDlgItem (parent, edt1);
999 if (textfield == NULL)
1000 return FALSE;
1001 HWND selector = ::GetDlgItem (parent, cmb1);
1002
1003 /* simulate filter change by pressing apply-key */
1004 int size = 256;
1005 TCHAR *buffer = (TCHAR*)malloc (size);
1006 SendMessage (textfield, WM_GETTEXT, size, (LPARAM)buffer);
1007 SendMessage (textfield, WM_SETTEXT, 0, (LPARAM)"\0");
1008 SendMessage (button, BM_CLICK, 0, 0);
1009 SendMessage (textfield, WM_SETTEXT, 0, (LPARAM)buffer);
1010 free (buffer);
1011
1012 /* make request for focus moving to filter selector combo-box */
1013 HWND curFocus = GetFocus();
1014 PostMessage (curFocus, WM_KILLFOCUS, (WPARAM)selector, 0);
1015 PostMessage (selector, WM_SETFOCUS, (WPARAM)curFocus, 0);
1016 WPARAM wParam = MAKEWPARAM (WA_ACTIVE, 0);
1017 PostMessage (selector, WM_ACTIVATE, wParam, (LPARAM)curFocus);
1018 }
1019 }
1020 return FALSE;
1021}
1022
1023/*
1024 * Callback function to control the native Win32 API folders dialog
1025 */
1026static int __stdcall winGetExistDirCallbackProc (HWND hwnd, UINT uMsg,
1027 LPARAM lParam, LPARAM lpData)
1028{
1029 if (uMsg == BFFM_INITIALIZED && lpData != 0)
1030 {
1031 QString *initDir = (QString *)(lpData);
1032 if (!initDir->isEmpty())
1033 {
1034 SendMessage (hwnd, BFFM_SETSELECTION, TRUE, Q_ULONG (
1035 initDir->isNull() ? 0 : initDir->utf16()));
1036 //SendMessage (hwnd, BFFM_SETEXPANDED, TRUE, Q_ULONG (initDir->utf16()));
1037 }
1038 }
1039 else if (uMsg == BFFM_SELCHANGED)
1040 {
1041 TCHAR path [MAX_PATH];
1042 SHGetPathFromIDList (LPITEMIDLIST (lParam), path);
1043 QString tmpStr = QString::fromUtf16 ((ushort*)path);
1044 if (!tmpStr.isEmpty())
1045 SendMessage (hwnd, BFFM_ENABLEOK, 1, 1);
1046 else
1047 SendMessage (hwnd, BFFM_ENABLEOK, 0, 0);
1048 SendMessage (hwnd, BFFM_SETSTATUSTEXT, 1, Q_ULONG (path));
1049 }
1050 return 0;
1051}
1052
1053/**
1054 * QEvent class to carry Win32 API native dialog's result information
1055 */
1056class OpenNativeDialogEvent : public QEvent
1057{
1058public:
1059
1060 OpenNativeDialogEvent (const QString &aResult, QEvent::Type aType)
1061 : QEvent (aType), mResult (aResult) {}
1062
1063 const QString& result() { return mResult; }
1064
1065private:
1066
1067 QString mResult;
1068};
1069
1070/**
1071 * QObject class reimplementation which is the target for OpenNativeDialogEvent
1072 * event. It receives OpenNativeDialogEvent event from another thread,
1073 * stores result information and exits the given local event loop.
1074 */
1075class LoopObject : public QObject
1076{
1077public:
1078
1079 LoopObject (QEvent::Type aType, QEventLoop &aLoop)
1080 : mType (aType), mLoop (aLoop), mResult (QString::null) {}
1081 const QString& result() { return mResult; }
1082
1083private:
1084
1085 bool event (QEvent *aEvent)
1086 {
1087 if (aEvent->type() == mType)
1088 {
1089 OpenNativeDialogEvent *ev = (OpenNativeDialogEvent*) aEvent;
1090 mResult = ev->result();
1091 mLoop.quit();
1092 return true;
1093 }
1094 return QObject::event (aEvent);
1095 }
1096
1097 QEvent::Type mType;
1098 QEventLoop &mLoop;
1099 QString mResult;
1100};
1101
1102#endif /* Q_WS_WIN */
1103
1104
1105// VBoxGlobal
1106////////////////////////////////////////////////////////////////////////////////
1107
1108static bool sVBoxGlobalInited = false;
1109static bool sVBoxGlobalInCleanup = false;
1110
1111/** @internal
1112 *
1113 * Special routine to do VBoxGlobal cleanup when the application is being
1114 * terminated. It is called before some essential Qt functionality (for
1115 * instance, QThread) becomes unavailable, allowing us to use it from
1116 * VBoxGlobal::cleanup() if necessary.
1117 */
1118static void vboxGlobalCleanup()
1119{
1120 Assert (!sVBoxGlobalInCleanup);
1121 sVBoxGlobalInCleanup = true;
1122 vboxGlobal().cleanup();
1123}
1124
1125/** @internal
1126 *
1127 * Determines the rendering mode from the argument. Sets the appropriate
1128 * default rendering mode if the argumen is NULL.
1129 */
1130static VBoxDefs::RenderMode vboxGetRenderMode (const char *aModeStr)
1131{
1132 VBoxDefs::RenderMode mode = VBoxDefs::InvalidRenderMode;
1133
1134#if defined (Q_WS_MAC) && defined (VBOX_GUI_USE_QUARTZ2D)
1135 mode = VBoxDefs::Quartz2DMode;
1136#elif (defined (Q_WS_WIN32) || defined (Q_WS_PM)) && defined (VBOX_GUI_USE_QIMAGE)
1137 mode = VBoxDefs::QImageMode;
1138#elif defined (Q_WS_X11) && defined (VBOX_GUI_USE_SDL)
1139 mode = VBoxDefs::SDLMode;
1140#elif defined (VBOX_GUI_USE_QIMAGE)
1141 mode = VBoxDefs::QImageMode;
1142#else
1143# error "Cannot determine the default render mode!"
1144#endif
1145
1146 if (aModeStr)
1147 {
1148 if (0) ;
1149#if defined (VBOX_GUI_USE_QIMAGE)
1150 else if (::strcmp (aModeStr, "image") == 0)
1151 mode = VBoxDefs::QImageMode;
1152#endif
1153#if defined (VBOX_GUI_USE_SDL)
1154 else if (::strcmp (aModeStr, "sdl") == 0)
1155 mode = VBoxDefs::SDLMode;
1156#endif
1157#if defined (VBOX_GUI_USE_DDRAW)
1158 else if (::strcmp (aModeStr, "ddraw") == 0)
1159 mode = VBoxDefs::DDRAWMode;
1160#endif
1161#if defined (VBOX_GUI_USE_QUARTZ2D)
1162 else if (::strcmp (aModeStr, "quartz2d") == 0)
1163 mode = VBoxDefs::Quartz2DMode;
1164#endif
1165 }
1166
1167 return mode;
1168}
1169
1170/** @class VBoxGlobal
1171 *
1172 * The VBoxGlobal class incapsulates the global VirtualBox data.
1173 *
1174 * There is only one instance of this class per VirtualBox application,
1175 * the reference to it is returned by the static instance() method, or by
1176 * the global vboxGlobal() function, that is just an inlined shortcut.
1177 */
1178
1179VBoxGlobal::VBoxGlobal()
1180 : mValid (false)
1181 , mSelectorWnd (NULL), mConsoleWnd (NULL)
1182 , mMainWindow (NULL)
1183#ifdef VBOX_WITH_REGISTRATION
1184 , mRegDlg (NULL)
1185#endif
1186 , mUpdDlg (NULL)
1187 , mMediaEnumThread (NULL)
1188 , verString ("1.0")
1189 , vm_state_color (KMachineState_COUNT)
1190 , machineStates (KMachineState_COUNT)
1191 , sessionStates (KSessionState_COUNT)
1192 , deviceTypes (KDeviceType_COUNT)
1193 , storageBuses (KStorageBus_COUNT)
1194 , storageBusDevices (2)
1195 , storageBusChannels (3)
1196 , diskTypes (KHardDiskType_COUNT)
1197 , vrdpAuthTypes (KVRDPAuthType_COUNT)
1198 , portModeTypes (KPortMode_COUNT)
1199 , usbFilterActionTypes (KUSBDeviceFilterAction_COUNT)
1200 , audioDriverTypes (KAudioDriverType_COUNT)
1201 , audioControllerTypes (KAudioControllerType_COUNT)
1202 , networkAdapterTypes (KNetworkAdapterType_COUNT)
1203 , networkAttachmentTypes (KNetworkAttachmentType_COUNT)
1204 , clipboardTypes (KClipboardMode_COUNT)
1205 , ideControllerTypes (KIDEControllerType_COUNT)
1206 , USBDeviceStates (KUSBDeviceState_COUNT)
1207 , detailReportTemplatesReady (false)
1208{
1209}
1210
1211//
1212// Public members
1213/////////////////////////////////////////////////////////////////////////////
1214
1215/**
1216 * Returns a reference to the global VirtualBox data, managed by this class.
1217 *
1218 * The main() function of the VBox GUI must call this function soon after
1219 * creating a QApplication instance but before opening any of the main windows
1220 * (to let the VBoxGlobal initialization procedure use various Qt facilities),
1221 * and continue execution only when the isValid() method of the returned
1222 * instancereturns true, i.e. do something like:
1223 *
1224 * @code
1225 * if ( !VBoxGlobal::instance().isValid() )
1226 * return 1;
1227 * @endcode
1228 * or
1229 * @code
1230 * if ( !vboxGlobal().isValid() )
1231 * return 1;
1232 * @endcode
1233 *
1234 * @note Some VBoxGlobal methods can be used on a partially constructed
1235 * VBoxGlobal instance, i.e. from constructors and methods called
1236 * from the VBoxGlobal::init() method, which obtain the instance
1237 * using this instance() call or the ::vboxGlobal() function. Currently, such
1238 * methods are:
1239 * #vmStateText, #vmTypeIcon, #vmTypeText, #vmTypeTextList, #vmTypeFromText.
1240 *
1241 * @see ::vboxGlobal
1242 */
1243VBoxGlobal &VBoxGlobal::instance()
1244{
1245 static VBoxGlobal vboxGlobal_instance;
1246
1247 if (!sVBoxGlobalInited)
1248 {
1249 /* check that a QApplication instance is created */
1250 if (qApp)
1251 {
1252 sVBoxGlobalInited = true;
1253 vboxGlobal_instance.init();
1254 /* add our cleanup handler to the list of Qt post routines */
1255 qAddPostRoutine (vboxGlobalCleanup);
1256 }
1257 else
1258 AssertMsgFailed (("Must construct a QApplication first!"));
1259 }
1260 return vboxGlobal_instance;
1261}
1262
1263VBoxGlobal::~VBoxGlobal()
1264{
1265 qDeleteAll (vm_os_type_icons);
1266 qDeleteAll (mStateIcons);
1267 qDeleteAll (vm_state_color);
1268}
1269
1270/**
1271 * Sets the new global settings and saves them to the VirtualBox server.
1272 */
1273bool VBoxGlobal::setSettings (const VBoxGlobalSettings &gs)
1274{
1275 gs.save (mVBox);
1276
1277 if (!mVBox.isOk())
1278 {
1279 vboxProblem().cannotSaveGlobalConfig (mVBox);
1280 return false;
1281 }
1282
1283 /* We don't assign gs to our gset member here, because VBoxCallback
1284 * will update gset as necessary when new settings are successfullly
1285 * sent to the VirtualBox server by gs.save(). */
1286
1287 return true;
1288}
1289
1290/**
1291 * Returns a reference to the main VBox VM Selector window.
1292 * The reference is valid until application termination.
1293 *
1294 * There is only one such a window per VirtualBox application.
1295 */
1296VBoxSelectorWnd &VBoxGlobal::selectorWnd()
1297{
1298#if defined (VBOX_GUI_SEPARATE_VM_PROCESS)
1299 AssertMsg (!vboxGlobal().isVMConsoleProcess(),
1300 ("Must NOT be a VM console process"));
1301#endif
1302
1303 Assert (mValid);
1304
1305 if (!mSelectorWnd)
1306 {
1307 /*
1308 * We pass the address of mSelectorWnd to the constructor to let it be
1309 * initialized right after the constructor is called. It is necessary
1310 * to avoid recursion, since this method may be (and will be) called
1311 * from the below constructor or from constructors/methods it calls.
1312 */
1313 VBoxSelectorWnd *w = new VBoxSelectorWnd (&mSelectorWnd, 0);
1314 Assert (w == mSelectorWnd);
1315 NOREF(w);
1316 }
1317
1318 return *mSelectorWnd;
1319}
1320
1321/**
1322 * Returns a reference to the main VBox VM Console window.
1323 * The reference is valid until application termination.
1324 *
1325 * There is only one such a window per VirtualBox application.
1326 */
1327VBoxConsoleWnd &VBoxGlobal::consoleWnd()
1328{
1329#if defined (VBOX_GUI_SEPARATE_VM_PROCESS)
1330 AssertMsg (vboxGlobal().isVMConsoleProcess(),
1331 ("Must be a VM console process"));
1332#endif
1333
1334 Assert (mValid);
1335
1336 if (!mConsoleWnd)
1337 {
1338 /*
1339 * We pass the address of mConsoleWnd to the constructor to let it be
1340 * initialized right after the constructor is called. It is necessary
1341 * to avoid recursion, since this method may be (and will be) called
1342 * from the below constructor or from constructors/methods it calls.
1343 */
1344 VBoxConsoleWnd *w = new VBoxConsoleWnd (&mConsoleWnd, 0);
1345 Assert (w == mConsoleWnd);
1346 NOREF(w);
1347 }
1348
1349 return *mConsoleWnd;
1350}
1351
1352/**
1353 * Returns the list of all guest OS type descriptions, queried from
1354 * IVirtualBox.
1355 */
1356QStringList VBoxGlobal::vmGuestOSTypeDescriptions() const
1357{
1358 static QStringList list;
1359 if (list.empty()) {
1360 for (int i = 0; i < vm_os_types.count(); i++) {
1361 list += vm_os_types [i].GetDescription();
1362 }
1363 }
1364 return list;
1365}
1366
1367QList<QPixmap> VBoxGlobal::vmGuestOSTypeIcons (int aHorizonalMargin, int aVerticalMargin) const
1368{
1369 static QList<QPixmap> list;
1370 if (list.empty())
1371 {
1372 for (int i = 0; i < vm_os_types.count(); i++)
1373 {
1374 QPixmap image (32 + 2 * aHorizonalMargin, 32 + 2 * aVerticalMargin);
1375 image.fill (Qt::transparent);
1376 QPainter p (&image);
1377 p.drawPixmap (aHorizonalMargin, aVerticalMargin, *vm_os_type_icons.value (vm_os_types [i].GetId()));
1378 p.end();
1379 list << image;
1380 }
1381 }
1382 return list;
1383}
1384
1385/**
1386 * Returns the guest OS type object corresponding to the given index.
1387 * The index argument corresponds to the index in the list of OS type
1388 * descriptions as returnded by #vmGuestOSTypeDescriptions().
1389 *
1390 * If the index is invalid a null object is returned.
1391 */
1392CGuestOSType VBoxGlobal::vmGuestOSType (int aIndex) const
1393{
1394 CGuestOSType type;
1395 if (aIndex >= 0 && aIndex < (int) vm_os_types.count())
1396 type = vm_os_types.value (aIndex);
1397 AssertMsg (!type.isNull(), ("Index for OS type must be valid: %d", aIndex));
1398 return type;
1399}
1400
1401/**
1402 * Returns the index corresponding to the given guest OS type ID.
1403 * The returned index corresponds to the index in the list of OS type
1404 * descriptions as returnded by #vmGuestOSTypeDescriptions().
1405 *
1406 * If the guest OS type ID is invalid, -1 is returned.
1407 */
1408int VBoxGlobal::vmGuestOSTypeIndex (const QString &aId) const
1409{
1410 for (int i = 0; i < (int) vm_os_types.count(); i++) {
1411 if (!vm_os_types [i].GetId().compare (aId))
1412 return i;
1413 }
1414 return -1;
1415}
1416
1417/**
1418 * Returns the icon corresponding to the given guest OS type ID.
1419 */
1420QPixmap VBoxGlobal::vmGuestOSTypeIcon (const QString &aId) const
1421{
1422 static const QPixmap none;
1423 QPixmap *p = vm_os_type_icons.value (aId);
1424 AssertMsg (p, ("Icon for type `%s' must be defined", aId.toLatin1().constData()));
1425 return p ? *p : none;
1426}
1427
1428/**
1429 * Returns the description corresponding to the given guest OS type ID.
1430 */
1431QString VBoxGlobal::vmGuestOSTypeDescription (const QString &aId) const
1432{
1433 for (int i = 0; i < (int) vm_os_types.count(); i++) {
1434 if (!vm_os_types [i].GetId().compare (aId))
1435 return vm_os_types [i].GetDescription();
1436 }
1437 return QString::null;
1438}
1439
1440/**
1441 * Returns a string representation of the given channel number on the given
1442 * storage bus. Complementary to #toStorageChannel (KStorageBus, const
1443 * QString &) const.
1444 */
1445QString VBoxGlobal::toString (KStorageBus aBus, LONG aChannel) const
1446{
1447 Assert (storageBusChannels.count() == 3);
1448 QString channel;
1449
1450 switch (aBus)
1451 {
1452 case KStorageBus_IDE:
1453 {
1454 if (aChannel == 0 || aChannel == 1)
1455 {
1456 channel = storageBusChannels [aChannel];
1457 break;
1458 }
1459
1460 AssertMsgFailedBreak (("Invalid channel %d\n", aChannel));
1461 }
1462 case KStorageBus_SATA:
1463 {
1464 channel = storageBusChannels [2].arg (aChannel);
1465 break;
1466 }
1467 default:
1468 AssertFailedBreak();
1469 }
1470
1471 return channel;
1472}
1473
1474/**
1475 * Returns a channel number on the given storage bus corresponding to the given
1476 * string representation. Complementary to #toString (KStorageBus, LONG) const.
1477 */
1478LONG VBoxGlobal::toStorageChannel (KStorageBus aBus, const QString &aChannel) const
1479{
1480 LONG channel = 0;
1481
1482 switch (aBus)
1483 {
1484 case KStorageBus_IDE:
1485 {
1486 QStringVector::const_iterator it =
1487 qFind (storageBusChannels.begin(), storageBusChannels.end(),
1488 aChannel);
1489 AssertMsgBreak (it != storageBusChannels.end(),
1490 ("No value for {%s}\n", aChannel.toLatin1().constData()));
1491 channel = (LONG) (it - storageBusChannels.begin());
1492 break;
1493 }
1494 case KStorageBus_SATA:
1495 {
1496 /// @todo use regexp to properly extract the %1 text
1497 QString tpl = storageBusChannels [2].arg ("");
1498 if (aChannel.startsWith (tpl))
1499 {
1500 channel = aChannel.right (aChannel.length() - tpl.length()).toLong();
1501 break;
1502 }
1503
1504 AssertMsgFailedBreak (("Invalid channel {%s}\n", aChannel.toLatin1().constData()));
1505 break;
1506 }
1507 default:
1508 AssertFailedBreak();
1509 }
1510
1511 return channel;
1512}
1513
1514/**
1515 * Returns a string representation of the given device number of the given
1516 * channel on the given storage bus. Complementary to #toStorageDevice
1517 * (KStorageBus, LONG, const QString &) const.
1518 */
1519QString VBoxGlobal::toString (KStorageBus aBus, LONG aChannel, LONG aDevice) const
1520{
1521 NOREF (aChannel);
1522
1523 Assert (storageBusDevices.count() == 2);
1524 QString device;
1525
1526 switch (aBus)
1527 {
1528 case KStorageBus_IDE:
1529 {
1530 if (aDevice == 0 || aDevice == 1)
1531 {
1532 device = storageBusDevices [aDevice];
1533 break;
1534 }
1535
1536 AssertMsgFailedBreak (("Invalid device %d\n", aDevice));
1537 }
1538 case KStorageBus_SATA:
1539 {
1540 AssertMsgBreak (aDevice == 0, ("Invalid device %d\n", aDevice));
1541 /* always zero so far for SATA */
1542 break;
1543 }
1544 default:
1545 AssertFailedBreak();
1546 }
1547
1548 return device;
1549}
1550
1551/**
1552 * Returns a device number of the given channel on the given storage bus
1553 * corresponding to the given string representation. Complementary to #toString
1554 * (KStorageBus, LONG, LONG) const.
1555 */
1556LONG VBoxGlobal::toStorageDevice (KStorageBus aBus, LONG aChannel,
1557 const QString &aDevice) const
1558{
1559 NOREF (aChannel);
1560
1561 LONG device = 0;
1562
1563 switch (aBus)
1564 {
1565 case KStorageBus_IDE:
1566 {
1567 QStringVector::const_iterator it =
1568 qFind (storageBusDevices.begin(), storageBusDevices.end(),
1569 aDevice);
1570 AssertMsg (it != storageBusDevices.end(),
1571 ("No value for {%s}", aDevice.toLatin1().constData()));
1572 device = (LONG) (it - storageBusDevices.begin());
1573 break;
1574 }
1575 case KStorageBus_SATA:
1576 {
1577 AssertMsgBreak(aDevice.isEmpty(), ("Invalid device {%s}\n", aDevice.toLatin1().constData()));
1578 /* always zero for SATA so far. */
1579 break;
1580 }
1581 default:
1582 AssertFailedBreak();
1583 }
1584
1585 return device;
1586}
1587
1588/**
1589 * Returns a full string representation of the given device of the given channel
1590 * on the given storage bus. Complementary to #toStorageParams (KStorageBus,
1591 * LONG, LONG) const.
1592 */
1593QString VBoxGlobal::toFullString (KStorageBus aBus, LONG aChannel,
1594 LONG aDevice) const
1595{
1596 QString device;
1597
1598 switch (aBus)
1599 {
1600 case KStorageBus_IDE:
1601 {
1602 device = QString ("%1 %2 %3")
1603 .arg (vboxGlobal().toString (aBus))
1604 .arg (vboxGlobal().toString (aBus, aChannel))
1605 .arg (vboxGlobal().toString (aBus, aChannel, aDevice));
1606 break;
1607 }
1608 case KStorageBus_SATA:
1609 {
1610 /* we only have one SATA device so far which is always zero */
1611 device = QString ("%1 %2")
1612 .arg (vboxGlobal().toString (aBus))
1613 .arg (vboxGlobal().toString (aBus, aChannel));
1614 break;
1615 }
1616 default:
1617 AssertFailedBreak();
1618 }
1619
1620 return device;
1621}
1622
1623/**
1624 * Returns the list of all device types (VirtualBox::DeviceType COM enum).
1625 */
1626QStringList VBoxGlobal::deviceTypeStrings() const
1627{
1628 static QStringList list;
1629 if (list.empty())
1630 for (int i = 0; i < deviceTypes.count() - 1 /* usb=n/a */; i++)
1631 list += deviceTypes [i];
1632 return list;
1633}
1634
1635struct PortConfig
1636{
1637 const char *name;
1638 const ulong IRQ;
1639 const ulong IOBase;
1640};
1641
1642static const PortConfig comKnownPorts[] =
1643{
1644 { "COM1", 4, 0x3F8 },
1645 { "COM2", 3, 0x2F8 },
1646 { "COM3", 4, 0x3E8 },
1647 { "COM4", 3, 0x2E8 },
1648 /* must not contain an element with IRQ=0 and IOBase=0 used to cause
1649 * toCOMPortName() to return the "User-defined" string for these values. */
1650};
1651
1652static const PortConfig lptKnownPorts[] =
1653{
1654 { "LPT1", 7, 0x3BC },
1655 { "LPT2", 5, 0x378 },
1656 { "LPT3", 5, 0x278 },
1657 /* must not contain an element with IRQ=0 and IOBase=0 used to cause
1658 * toLPTPortName() to return the "User-defined" string for these values. */
1659};
1660
1661/**
1662 * Returns the list of the standard COM port names (i.e. "COMx").
1663 */
1664QStringList VBoxGlobal::COMPortNames() const
1665{
1666 QStringList list;
1667 for (size_t i = 0; i < RT_ELEMENTS (comKnownPorts); ++ i)
1668 list << comKnownPorts [i].name;
1669
1670 return list;
1671}
1672
1673/**
1674 * Returns the list of the standard LPT port names (i.e. "LPTx").
1675 */
1676QStringList VBoxGlobal::LPTPortNames() const
1677{
1678 QStringList list;
1679 for (size_t i = 0; i < RT_ELEMENTS (lptKnownPorts); ++ i)
1680 list << lptKnownPorts [i].name;
1681
1682 return list;
1683}
1684
1685/**
1686 * Returns the name of the standard COM port corresponding to the given
1687 * parameters, or "User-defined" (which is also returned when both
1688 * @a aIRQ and @a aIOBase are 0).
1689 */
1690QString VBoxGlobal::toCOMPortName (ulong aIRQ, ulong aIOBase) const
1691{
1692 for (size_t i = 0; i < RT_ELEMENTS (comKnownPorts); ++ i)
1693 if (comKnownPorts [i].IRQ == aIRQ &&
1694 comKnownPorts [i].IOBase == aIOBase)
1695 return comKnownPorts [i].name;
1696
1697 return mUserDefinedPortName;
1698}
1699
1700/**
1701 * Returns the name of the standard LPT port corresponding to the given
1702 * parameters, or "User-defined" (which is also returned when both
1703 * @a aIRQ and @a aIOBase are 0).
1704 */
1705QString VBoxGlobal::toLPTPortName (ulong aIRQ, ulong aIOBase) const
1706{
1707 for (size_t i = 0; i < RT_ELEMENTS (lptKnownPorts); ++ i)
1708 if (lptKnownPorts [i].IRQ == aIRQ &&
1709 lptKnownPorts [i].IOBase == aIOBase)
1710 return lptKnownPorts [i].name;
1711
1712 return mUserDefinedPortName;
1713}
1714
1715/**
1716 * Returns port parameters corresponding to the given standard COM name.
1717 * Returns @c true on success, or @c false if the given port name is not one
1718 * of the standard names (i.e. "COMx").
1719 */
1720bool VBoxGlobal::toCOMPortNumbers (const QString &aName, ulong &aIRQ,
1721 ulong &aIOBase) const
1722{
1723 for (size_t i = 0; i < RT_ELEMENTS (comKnownPorts); ++ i)
1724 if (strcmp (comKnownPorts [i].name, aName.toUtf8().data()) == 0)
1725 {
1726 aIRQ = comKnownPorts [i].IRQ;
1727 aIOBase = comKnownPorts [i].IOBase;
1728 return true;
1729 }
1730
1731 return false;
1732}
1733
1734/**
1735 * Returns port parameters corresponding to the given standard LPT name.
1736 * Returns @c true on success, or @c false if the given port name is not one
1737 * of the standard names (i.e. "LPTx").
1738 */
1739bool VBoxGlobal::toLPTPortNumbers (const QString &aName, ulong &aIRQ,
1740 ulong &aIOBase) const
1741{
1742 for (size_t i = 0; i < RT_ELEMENTS (lptKnownPorts); ++ i)
1743 if (strcmp (lptKnownPorts [i].name, aName.toUtf8().data()) == 0)
1744 {
1745 aIRQ = lptKnownPorts [i].IRQ;
1746 aIOBase = lptKnownPorts [i].IOBase;
1747 return true;
1748 }
1749
1750 return false;
1751}
1752
1753/**
1754 * Searches for the given hard disk in the list of known media descriptors and
1755 * calls VBoxMedium::details() on the found desriptor.
1756 *
1757 * If the requeststed hard disk is not found (for example, it's a new hard disk
1758 * for a new VM created outside our UI), then media enumeration is requested and
1759 * the search is repeated. We assume that the secont attempt always succeeds and
1760 * assert otherwise.
1761 *
1762 * @note Technically, the second attempt may fail if, for example, the new hard
1763 * passed to this method disk gets removed before #startEnumeratingMedia()
1764 * succeeds. This (unexpected object uninitialization) is a generic
1765 * problem though and needs to be addressed using exceptions (see also the
1766 * @todo in VBoxMedium::details()).
1767 */
1768QString VBoxGlobal::details (const CHardDisk2 &aHD,
1769 bool aPredictDiff)
1770{
1771 CMedium cmedium (aHD);
1772 VBoxMedium medium;
1773
1774 if (!findMedium (cmedium, medium))
1775 {
1776 /* media may be new and not alredy in the media list, request refresh */
1777 startEnumeratingMedia();
1778 if (!findMedium (cmedium, medium))
1779 AssertFailedReturn (QString::null);
1780 }
1781
1782 return medium.detailsHTML (true /* aNoDiffs */, aPredictDiff);
1783}
1784
1785/**
1786 * Returns the details of the given USB device as a single-line string.
1787 */
1788QString VBoxGlobal::details (const CUSBDevice &aDevice) const
1789{
1790 QString details;
1791 QString m = aDevice.GetManufacturer().trimmed();
1792 QString p = aDevice.GetProduct().trimmed();
1793 if (m.isEmpty() && p.isEmpty())
1794 {
1795 details =
1796 tr ("Unknown device %1:%2", "USB device details")
1797 .arg (QString().sprintf ("%04hX", aDevice.GetVendorId()))
1798 .arg (QString().sprintf ("%04hX", aDevice.GetProductId()));
1799 }
1800 else
1801 {
1802 if (p.toUpper().startsWith (m.toUpper()))
1803 details = p;
1804 else
1805 details = m + " " + p;
1806 }
1807 ushort r = aDevice.GetRevision();
1808 if (r != 0)
1809 details += QString().sprintf (" [%04hX]", r);
1810
1811 return details.trimmed();
1812}
1813
1814/**
1815 * Returns the multi-line description of the given USB device.
1816 */
1817QString VBoxGlobal::toolTip (const CUSBDevice &aDevice) const
1818{
1819 QString tip =
1820 tr ("<nobr>Vendor ID: %1</nobr><br>"
1821 "<nobr>Product ID: %2</nobr><br>"
1822 "<nobr>Revision: %3</nobr>", "USB device tooltip")
1823 .arg (QString().sprintf ("%04hX", aDevice.GetVendorId()))
1824 .arg (QString().sprintf ("%04hX", aDevice.GetProductId()))
1825 .arg (QString().sprintf ("%04hX", aDevice.GetRevision()));
1826
1827 QString ser = aDevice.GetSerialNumber();
1828 if (!ser.isEmpty())
1829 tip += QString (tr ("<br><nobr>Serial No. %1</nobr>", "USB device tooltip"))
1830 .arg (ser);
1831
1832 /* add the state field if it's a host USB device */
1833 CHostUSBDevice hostDev (aDevice);
1834 if (!hostDev.isNull())
1835 {
1836 tip += QString (tr ("<br><nobr>State: %1</nobr>", "USB device tooltip"))
1837 .arg (vboxGlobal().toString (hostDev.GetState()));
1838 }
1839
1840 return tip;
1841}
1842
1843/**
1844 * Returns the multi-line description of the given USB filter
1845 */
1846QString VBoxGlobal::toolTip (const CUSBDeviceFilter &aFilter) const
1847{
1848 QString tip;
1849
1850 QString vendorId = aFilter.GetVendorId();
1851 if (!vendorId.isEmpty())
1852 tip += tr ("<nobr>Vendor ID: %1</nobr>", "USB filter tooltip")
1853 .arg (vendorId);
1854
1855 QString productId = aFilter.GetProductId();
1856 if (!productId.isEmpty())
1857 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Product ID: %2</nobr>", "USB filter tooltip")
1858 .arg (productId);
1859
1860 QString revision = aFilter.GetRevision();
1861 if (!revision.isEmpty())
1862 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Revision: %3</nobr>", "USB filter tooltip")
1863 .arg (revision);
1864
1865 QString product = aFilter.GetProduct();
1866 if (!product.isEmpty())
1867 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Product: %4</nobr>", "USB filter tooltip")
1868 .arg (product);
1869
1870 QString manufacturer = aFilter.GetManufacturer();
1871 if (!manufacturer.isEmpty())
1872 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Manufacturer: %5</nobr>", "USB filter tooltip")
1873 .arg (manufacturer);
1874
1875 QString serial = aFilter.GetSerialNumber();
1876 if (!serial.isEmpty())
1877 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Serial No.: %1</nobr>", "USB filter tooltip")
1878 .arg (serial);
1879
1880 QString port = aFilter.GetPort();
1881 if (!port.isEmpty())
1882 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>Port: %1</nobr>", "USB filter tooltip")
1883 .arg (port);
1884
1885 /* add the state field if it's a host USB device */
1886 CHostUSBDevice hostDev (aFilter);
1887 if (!hostDev.isNull())
1888 {
1889 tip += tip.isEmpty() ? "":"<br/>" + tr ("<nobr>State: %1</nobr>", "USB filter tooltip")
1890 .arg (vboxGlobal().toString (hostDev.GetState()));
1891 }
1892
1893 return tip;
1894}
1895
1896/**
1897 * Returns a details report on a given VM represented as a HTML table.
1898 *
1899 * @param aMachine Machine to create a report for.
1900 * @param aIsNewVM @c true when called by the New VM Wizard.
1901 * @param aWithLinks @c true if section titles should be hypertext links.
1902 */
1903QString VBoxGlobal::detailsReport (const CMachine &aMachine, bool aIsNewVM,
1904 bool aWithLinks)
1905{
1906 static const char *sTableTpl =
1907 "<table border=0 cellspacing=1 cellpadding=0>%1</table>";
1908 static const char *sSectionHrefTpl =
1909 "<tr><td width=22 rowspan=%1 align=left><img src='%2'></td>"
1910 "<td colspan=2><b><a href='%3'><nobr>%4</nobr></a></b></td></tr>"
1911 "%5"
1912 "<tr><td colspan=2><font size=1>&nbsp;</font></td></tr>";
1913 static const char *sSectionBoldTpl =
1914 "<tr><td width=22 rowspan=%1 align=left><img src='%2'></td>"
1915 "<td colspan=2><!-- %3 --><b><nobr>%4</nobr></b></td></tr>"
1916 "%5"
1917 "<tr><td colspan=2><font size=1>&nbsp;</font></td></tr>";
1918 static const char *sSectionItemTpl =
1919 "<tr><td width=40%><nobr>%1</nobr></td><td>%2</td></tr>";
1920
1921 static QString sGeneralBasicHrefTpl, sGeneralBasicBoldTpl;
1922 static QString sGeneralFullHrefTpl, sGeneralFullBoldTpl;
1923
1924 /* generate templates after every language change */
1925
1926 if (!detailReportTemplatesReady)
1927 {
1928 detailReportTemplatesReady = true;
1929
1930 QString generalItems
1931 = QString (sSectionItemTpl).arg (tr ("Name", "details report"), "%1")
1932 + QString (sSectionItemTpl).arg (tr ("OS Type", "details report"), "%2")
1933 + QString (sSectionItemTpl).arg (tr ("Base Memory", "details report"),
1934 tr ("<nobr>%3 MB</nobr>", "details report"));
1935 sGeneralBasicHrefTpl = QString (sSectionHrefTpl)
1936 .arg (2 + 3) /* rows */
1937 .arg (":/machine_16px.png", /* icon */
1938 "#general", /* link */
1939 tr ("General", "details report"), /* title */
1940 generalItems); /* items */
1941 sGeneralBasicBoldTpl = QString (sSectionBoldTpl)
1942 .arg (2 + 3) /* rows */
1943 .arg (":/machine_16px.png", /* icon */
1944 "#general", /* link */
1945 tr ("General", "details report"), /* title */
1946 generalItems); /* items */
1947
1948 generalItems
1949 += QString (sSectionItemTpl).arg (tr ("Video Memory", "details report"),
1950 tr ("<nobr>%4 MB</nobr>", "details report"))
1951 + QString (sSectionItemTpl).arg (tr ("Boot Order", "details report"), "%5")
1952 + QString (sSectionItemTpl).arg (tr ("ACPI", "details report"), "%6")
1953 + QString (sSectionItemTpl).arg (tr ("IO APIC", "details report"), "%7")
1954 + QString (sSectionItemTpl).arg (tr ("VT-x/AMD-V", "details report"), "%8")
1955 + QString (sSectionItemTpl).arg (tr ("PAE/NX", "details report"), "%9");
1956
1957 sGeneralFullHrefTpl = QString (sSectionHrefTpl)
1958 .arg (2 + 9) /* rows */
1959 .arg (":/machine_16px.png", /* icon */
1960 "#general", /* link */
1961 tr ("General", "details report"), /* title */
1962 generalItems); /* items */
1963 sGeneralFullBoldTpl = QString (sSectionBoldTpl)
1964 .arg (2 + 9) /* rows */
1965 .arg (":/machine_16px.png", /* icon */
1966 "#general", /* link */
1967 tr ("General", "details report"), /* title */
1968 generalItems); /* items */
1969 }
1970
1971 /* common generated content */
1972
1973 const QString &sectionTpl = aWithLinks
1974 ? sSectionHrefTpl
1975 : sSectionBoldTpl;
1976
1977 QString hardDisks;
1978 {
1979 int rows = 2; /* including section header and footer */
1980
1981 CHardDisk2AttachmentVector vec = aMachine.GetHardDisk2Attachments();
1982 for (size_t i = 0; i < (size_t) vec.size(); ++ i)
1983 {
1984 CHardDisk2Attachment hda = vec [i];
1985 CHardDisk2 hd = hda.GetHardDisk();
1986
1987 /// @todo for the explaination of the below isOk() checks, see ***
1988 /// in #details (const CHardDisk &, bool).
1989 if (hda.isOk())
1990 {
1991 KStorageBus bus = hda.GetBus();
1992 LONG channel = hda.GetChannel();
1993 LONG device = hda.GetDevice();
1994 hardDisks += QString (sSectionItemTpl)
1995 .arg (toFullString (bus, channel, device))
1996 .arg (details (hd, aIsNewVM));
1997 ++ rows;
1998 }
1999 }
2000
2001 if (hardDisks.isNull())
2002 {
2003 hardDisks = QString (sSectionItemTpl)
2004 .arg (tr ("Not Attached", "details report (HDDs)")).arg ("");
2005 ++ rows;
2006 }
2007
2008 hardDisks = sectionTpl
2009 .arg (rows) /* rows */
2010 .arg (":/hd_16px.png", /* icon */
2011 "#hdds", /* link */
2012 tr ("Hard Disks", "details report"), /* title */
2013 hardDisks); /* items */
2014 }
2015
2016 /* compose details report */
2017
2018 const QString &generalBasicTpl = aWithLinks
2019 ? sGeneralBasicHrefTpl
2020 : sGeneralBasicBoldTpl;
2021
2022 const QString &generalFullTpl = aWithLinks
2023 ? sGeneralFullHrefTpl
2024 : sGeneralFullBoldTpl;
2025
2026 QString detailsReport;
2027
2028 if (aIsNewVM)
2029 {
2030 detailsReport
2031 = generalBasicTpl
2032 .arg (aMachine.GetName())
2033 .arg (vmGuestOSTypeDescription (aMachine.GetOSTypeId()))
2034 .arg (aMachine.GetMemorySize())
2035 + hardDisks;
2036 }
2037 else
2038 {
2039 /* boot order */
2040 QString bootOrder;
2041 for (ulong i = 1; i <= mVBox.GetSystemProperties().GetMaxBootPosition(); i++)
2042 {
2043 KDeviceType device = aMachine.GetBootOrder (i);
2044 if (device == KDeviceType_Null)
2045 continue;
2046 if (!bootOrder.isEmpty())
2047 bootOrder += ", ";
2048 bootOrder += toString (device);
2049 }
2050 if (bootOrder.isEmpty())
2051 bootOrder = toString (KDeviceType_Null);
2052
2053 CBIOSSettings biosSettings = aMachine.GetBIOSSettings();
2054
2055 /* ACPI */
2056 QString acpi = biosSettings.GetACPIEnabled()
2057 ? tr ("Enabled", "details report (ACPI)")
2058 : tr ("Disabled", "details report (ACPI)");
2059
2060 /* IO APIC */
2061 QString ioapic = biosSettings.GetIOAPICEnabled()
2062 ? tr ("Enabled", "details report (IO APIC)")
2063 : tr ("Disabled", "details report (IO APIC)");
2064
2065 /* VT-x/AMD-V */
2066 QString virt = aMachine.GetHWVirtExEnabled() == KTSBool_True ?
2067 tr ("Enabled", "details report (VT-x/AMD-V)") :
2068 tr ("Disabled", "details report (VT-x/AMD-V)");
2069
2070 /* PAE/NX */
2071 QString pae = aMachine.GetPAEEnabled()
2072 ? tr ("Enabled", "details report (PAE/NX)")
2073 : tr ("Disabled", "details report (PAE/NX)");
2074
2075 /* General + Hard Disks */
2076 detailsReport
2077 = generalFullTpl
2078 .arg (aMachine.GetName())
2079 .arg (vmGuestOSTypeDescription (aMachine.GetOSTypeId()))
2080 .arg (aMachine.GetMemorySize())
2081 .arg (aMachine.GetVRAMSize())
2082 .arg (bootOrder)
2083 .arg (acpi)
2084 .arg (ioapic)
2085 .arg (virt)
2086 .arg (pae)
2087 + hardDisks;
2088
2089 QString item;
2090
2091 /* DVD */
2092 CDVDDrive dvd = aMachine.GetDVDDrive();
2093 item = QString (sSectionItemTpl);
2094 switch (dvd.GetState())
2095 {
2096 case KDriveState_NotMounted:
2097 item = item.arg (tr ("Not mounted", "details report (DVD)"), "");
2098 break;
2099 case KDriveState_ImageMounted:
2100 {
2101 CDVDImage2 img = dvd.GetImage();
2102 item = item.arg (tr ("Image", "details report (DVD)"),
2103 locationForHTML (img.GetName()));
2104 break;
2105 }
2106 case KDriveState_HostDriveCaptured:
2107 {
2108 CHostDVDDrive drv = dvd.GetHostDrive();
2109 QString drvName = drv.GetName();
2110 QString description = drv.GetDescription();
2111 QString fullName = description.isEmpty() ?
2112 drvName :
2113 QString ("%1 (%2)").arg (description, drvName);
2114 item = item.arg (tr ("Host Drive", "details report (DVD)"),
2115 fullName);
2116 break;
2117 }
2118 default:
2119 AssertMsgFailed (("Invalid DVD state: %d", dvd.GetState()));
2120 }
2121 detailsReport += sectionTpl
2122 .arg (2 + 1) /* rows */
2123 .arg (":/cd_16px.png", /* icon */
2124 "#dvd", /* link */
2125 tr ("CD/DVD-ROM", "details report"), /* title */
2126 item); // items
2127
2128 /* Floppy */
2129 CFloppyDrive floppy = aMachine.GetFloppyDrive();
2130 item = QString (sSectionItemTpl);
2131 switch (floppy.GetState())
2132 {
2133 case KDriveState_NotMounted:
2134 item = item.arg (tr ("Not mounted", "details report (floppy)"), "");
2135 break;
2136 case KDriveState_ImageMounted:
2137 {
2138 CFloppyImage2 img = floppy.GetImage();
2139 item = item.arg (tr ("Image", "details report (floppy)"),
2140 locationForHTML (img.GetName()));
2141 break;
2142 }
2143 case KDriveState_HostDriveCaptured:
2144 {
2145 CHostFloppyDrive drv = floppy.GetHostDrive();
2146 QString drvName = drv.GetName();
2147 QString description = drv.GetDescription();
2148 QString fullName = description.isEmpty() ?
2149 drvName :
2150 QString ("%1 (%2)").arg (description, drvName);
2151 item = item.arg (tr ("Host Drive", "details report (floppy)"),
2152 fullName);
2153 break;
2154 }
2155 default:
2156 AssertMsgFailed (("Invalid floppy state: %d", floppy.GetState()));
2157 }
2158 detailsReport += sectionTpl
2159 .arg (2 + 1) /* rows */
2160 .arg (":/fd_16px.png", /* icon */
2161 "#floppy", /* link */
2162 tr ("Floppy", "details report"), /* title */
2163 item); /* items */
2164
2165 /* audio */
2166 {
2167 CAudioAdapter audio = aMachine.GetAudioAdapter();
2168 int rows = audio.GetEnabled() ? 3 : 2;
2169 if (audio.GetEnabled())
2170 item = QString (sSectionItemTpl)
2171 .arg (tr ("Host Driver", "details report (audio)"),
2172 toString (audio.GetAudioDriver())) +
2173 QString (sSectionItemTpl)
2174 .arg (tr ("Controller", "details report (audio)"),
2175 toString (audio.GetAudioController()));
2176 else
2177 item = QString (sSectionItemTpl)
2178 .arg (tr ("Disabled", "details report (audio)"), "");
2179
2180 detailsReport += sectionTpl
2181 .arg (rows + 1) /* rows */
2182 .arg (":/sound_16px.png", /* icon */
2183 "#audio", /* link */
2184 tr ("Audio", "details report"), /* title */
2185 item); /* items */
2186 }
2187 /* network */
2188 {
2189 item = QString::null;
2190 ulong count = mVBox.GetSystemProperties().GetNetworkAdapterCount();
2191 int rows = 2; /* including section header and footer */
2192 for (ulong slot = 0; slot < count; slot ++)
2193 {
2194 CNetworkAdapter adapter = aMachine.GetNetworkAdapter (slot);
2195 if (adapter.GetEnabled())
2196 {
2197 KNetworkAttachmentType type = adapter.GetAttachmentType();
2198 QString attType = toString (adapter.GetAdapterType())
2199 .replace (QRegExp ("\\s\\(.+\\)"), " (%1)");
2200 /* don't use the adapter type string for types that have
2201 * an additional symbolic network/interface name field, use
2202 * this name instead */
2203 if (type == KNetworkAttachmentType_HostInterface)
2204 attType = attType.arg (tr ("host interface, %1",
2205 "details report (network)").arg (adapter.GetHostInterface()));
2206 else if (type == KNetworkAttachmentType_Internal)
2207 attType = attType.arg (tr ("internal network, '%1'",
2208 "details report (network)").arg (adapter.GetInternalNetwork()));
2209 else
2210 attType = attType.arg (vboxGlobal().toString (type));
2211
2212 item += QString (sSectionItemTpl)
2213 .arg (tr ("Adapter %1", "details report (network)")
2214 .arg (adapter.GetSlot() + 1))
2215 .arg (attType);
2216 ++ rows;
2217 }
2218 }
2219 if (item.isNull())
2220 {
2221 item = QString (sSectionItemTpl)
2222 .arg (tr ("Disabled", "details report (network)"), "");
2223 ++ rows;
2224 }
2225
2226 detailsReport += sectionTpl
2227 .arg (rows) /* rows */
2228 .arg (":/nw_16px.png", /* icon */
2229 "#network", /* link */
2230 tr ("Network", "details report"), /* title */
2231 item); /* items */
2232 }
2233 /* serial ports */
2234 {
2235 item = QString::null;
2236 ulong count = mVBox.GetSystemProperties().GetSerialPortCount();
2237 int rows = 2; /* including section header and footer */
2238 for (ulong slot = 0; slot < count; slot ++)
2239 {
2240 CSerialPort port = aMachine.GetSerialPort (slot);
2241 if (port.GetEnabled())
2242 {
2243 KPortMode mode = port.GetHostMode();
2244 QString data =
2245 toCOMPortName (port.GetIRQ(), port.GetIOBase()) + ", ";
2246 if (mode == KPortMode_HostPipe ||
2247 mode == KPortMode_HostDevice)
2248 data += QString ("%1 (<nobr>%2</nobr>)")
2249 .arg (vboxGlobal().toString (mode))
2250 .arg (QDir::toNativeSeparators (port.GetPath()));
2251 else
2252 data += toString (mode);
2253
2254 item += QString (sSectionItemTpl)
2255 .arg (tr ("Port %1", "details report (serial ports)")
2256 .arg (port.GetSlot() + 1))
2257 .arg (data);
2258 ++ rows;
2259 }
2260 }
2261 if (item.isNull())
2262 {
2263 item = QString (sSectionItemTpl)
2264 .arg (tr ("Disabled", "details report (serial ports)"), "");
2265 ++ rows;
2266 }
2267
2268 detailsReport += sectionTpl
2269 .arg (rows) /* rows */
2270 .arg (":/serial_port_16px.png", /* icon */
2271 "#serialPorts", /* link */
2272 tr ("Serial Ports", "details report"), /* title */
2273 item); /* items */
2274 }
2275 /* parallel ports */
2276 {
2277 item = QString::null;
2278 ulong count = mVBox.GetSystemProperties().GetParallelPortCount();
2279 int rows = 2; /* including section header and footer */
2280 for (ulong slot = 0; slot < count; slot ++)
2281 {
2282 CParallelPort port = aMachine.GetParallelPort (slot);
2283 if (port.GetEnabled())
2284 {
2285 QString data =
2286 toLPTPortName (port.GetIRQ(), port.GetIOBase()) +
2287 QString (" (<nobr>%1</nobr>)")
2288 .arg (QDir::toNativeSeparators (port.GetPath()));
2289
2290 item += QString (sSectionItemTpl)
2291 .arg (tr ("Port %1", "details report (parallel ports)")
2292 .arg (port.GetSlot() + 1))
2293 .arg (data);
2294 ++ rows;
2295 }
2296 }
2297 if (item.isNull())
2298 {
2299 item = QString (sSectionItemTpl)
2300 .arg (tr ("Disabled", "details report (parallel ports)"), "");
2301 ++ rows;
2302 }
2303
2304 /* Temporary disabled */
2305 QString dummy = sectionTpl /* detailsReport += sectionTpl */
2306 .arg (rows) /* rows */
2307 .arg (":/parallel_port_16px.png", /* icon */
2308 "#parallelPorts", /* link */
2309 tr ("Parallel Ports", "details report"), /* title */
2310 item); /* items */
2311 }
2312 /* USB */
2313 {
2314 CUSBController ctl = aMachine.GetUSBController();
2315 if (!ctl.isNull())
2316 {
2317 /* the USB controller may be unavailable (i.e. in VirtualBox OSE) */
2318
2319 if (ctl.GetEnabled())
2320 {
2321 CUSBDeviceFilterCollection coll = ctl.GetDeviceFilters();
2322 CUSBDeviceFilterEnumerator en = coll.Enumerate();
2323 uint active = 0;
2324 while (en.HasMore())
2325 if (en.GetNext().GetActive())
2326 active ++;
2327
2328 item = QString (sSectionItemTpl)
2329 .arg (tr ("Device Filters", "details report (USB)"),
2330 tr ("%1 (%2 active)", "details report (USB)")
2331 .arg (coll.GetCount()).arg (active));
2332 }
2333 else
2334 item = QString (sSectionItemTpl)
2335 .arg (tr ("Disabled", "details report (USB)"), "");
2336
2337 detailsReport += sectionTpl
2338 .arg (2 + 1) /* rows */
2339 .arg (":/usb_16px.png", /* icon */
2340 "#usb", /* link */
2341 tr ("USB", "details report"), /* title */
2342 item); /* items */
2343 }
2344 }
2345 /* Shared folders */
2346 {
2347 ulong count = aMachine.GetSharedFolders().GetCount();
2348 if (count > 0)
2349 {
2350 item = QString (sSectionItemTpl)
2351 .arg (tr ("Shared Folders", "details report (shared folders)"),
2352 tr ("%1", "details report (shadef folders)")
2353 .arg (count));
2354 }
2355 else
2356 item = QString (sSectionItemTpl)
2357 .arg (tr ("None", "details report (shared folders)"), "");
2358
2359 detailsReport += sectionTpl
2360 .arg (2 + 1) /* rows */
2361 .arg (":/shared_folder_16px.png", /* icon */
2362 "#sfolders", /* link */
2363 tr ("Shared Folders", "details report"), /* title */
2364 item); /* items */
2365 }
2366 /* VRDP */
2367 {
2368 CVRDPServer srv = aMachine.GetVRDPServer();
2369 if (!srv.isNull())
2370 {
2371 /* the VRDP server may be unavailable (i.e. in VirtualBox OSE) */
2372
2373 if (srv.GetEnabled())
2374 item = QString (sSectionItemTpl)
2375 .arg (tr ("VRDP Server Port", "details report (VRDP)"),
2376 tr ("%1", "details report (VRDP)")
2377 .arg (srv.GetPort()));
2378 else
2379 item = QString (sSectionItemTpl)
2380 .arg (tr ("Disabled", "details report (VRDP)"), "");
2381
2382 detailsReport += sectionTpl
2383 .arg (2 + 1) /* rows */
2384 .arg (":/vrdp_16px.png", /* icon */
2385 "#vrdp", /* link */
2386 tr ("Remote Display", "details report"), /* title */
2387 item); /* items */
2388 }
2389 }
2390 }
2391
2392 return QString (sTableTpl). arg (detailsReport);
2393}
2394
2395QString VBoxGlobal::platformInfo()
2396{
2397 QString platform;
2398
2399#if defined (Q_OS_WIN)
2400 platform = "win";
2401#elif defined (Q_OS_LINUX)
2402 platform = "linux";
2403#elif defined (Q_OS_MACX)
2404 platform = "macosx";
2405#elif defined (Q_OS_OS2)
2406 platform = "os2";
2407#elif defined (Q_OS_FREEBSD)
2408 platform = "freebsd";
2409#elif defined (Q_OS_SOLARIS)
2410 platform = "solaris";
2411#else
2412 platform = "unknown";
2413#endif
2414
2415 /* The format is <system>.<bitness> */
2416 platform += QString (".%1").arg (ARCH_BITS);
2417
2418 /* Add more system information */
2419#if defined (Q_OS_WIN)
2420 OSVERSIONINFO versionInfo;
2421 ZeroMemory (&versionInfo, sizeof (OSVERSIONINFO));
2422 versionInfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
2423 GetVersionEx (&versionInfo);
2424 int major = versionInfo.dwMajorVersion;
2425 int minor = versionInfo.dwMinorVersion;
2426 int build = versionInfo.dwBuildNumber;
2427 QString sp = QString::fromUtf16 ((ushort*)versionInfo.szCSDVersion);
2428
2429 QString distrib;
2430 if (major == 6)
2431 distrib = QString ("Windows Vista %1");
2432 else if (major == 5)
2433 {
2434 if (minor == 2)
2435 distrib = QString ("Windows Server 2003 %1");
2436 else if (minor == 1)
2437 distrib = QString ("Windows XP %1");
2438 else if (minor == 0)
2439 distrib = QString ("Windows 2000 %1");
2440 else
2441 distrib = QString ("Unknown %1");
2442 }
2443 else if (major == 4)
2444 {
2445 if (minor == 90)
2446 distrib = QString ("Windows Me %1");
2447 else if (minor == 10)
2448 distrib = QString ("Windows 98 %1");
2449 else if (minor == 0)
2450 distrib = QString ("Windows 95 %1");
2451 else
2452 distrib = QString ("Unknown %1");
2453 }
2454 else
2455 distrib = QString ("Unknown %1");
2456 distrib = distrib.arg (sp);
2457 QString version = QString ("%1.%2").arg (major).arg (minor);
2458 QString kernel = QString ("%1").arg (build);
2459 platform += QString (" [Distribution: %1 | Version: %2 | Build: %3]")
2460 .arg (distrib).arg (version).arg (kernel);
2461#elif defined (Q_OS_OS2)
2462 // TODO: add sys info for os2 if any...
2463#elif defined (Q_OS_LINUX) || defined (Q_OS_MACX) || defined (Q_OS_FREEBSD) || defined (Q_OS_SOLARIS)
2464 /* Get script path */
2465 char szAppPrivPath [RTPATH_MAX];
2466 int rc = RTPathAppPrivateNoArch (szAppPrivPath, sizeof (szAppPrivPath)); NOREF(rc);
2467 AssertRC (rc);
2468 /* Run script */
2469 QByteArray result =
2470 Process::singleShot (QString (szAppPrivPath) + "/VBoxSysInfo.sh");
2471 if (!result.isNull())
2472 platform += QString (" [%1]").arg (QString (result).trimmed());
2473#endif
2474
2475 return platform;
2476}
2477
2478#if defined(Q_WS_X11) && !defined(VBOX_OSE)
2479double VBoxGlobal::findLicenseFile (const QStringList &aFilesList, QRegExp aPattern, QString &aLicenseFile) const
2480{
2481 double maxVersionNumber = 0;
2482 aLicenseFile = "";
2483 for (int index = 0; index < aFilesList.count(); ++ index)
2484 {
2485 aPattern.indexIn (aFilesList [index]);
2486 QString version = aPattern.cap (1);
2487 if (maxVersionNumber < version.toDouble())
2488 {
2489 maxVersionNumber = version.toDouble();
2490 aLicenseFile = aFilesList [index];
2491 }
2492 }
2493 return maxVersionNumber;
2494}
2495
2496bool VBoxGlobal::showVirtualBoxLicense()
2497{
2498 /* get the apps doc path */
2499 int size = 256;
2500 char *buffer = (char*) RTMemTmpAlloc (size);
2501 RTPathAppDocs (buffer, size);
2502 QString path (buffer);
2503 RTMemTmpFree (buffer);
2504 QDir docDir (path);
2505 docDir.setFilter (QDir::Files);
2506 docDir.setNameFilters (QStringList ("License-*.html"));
2507
2508 /* Make sure that the language is in two letter code.
2509 * Note: if languageId() returns an empty string lang.name() will
2510 * return "C" which is an valid language code. */
2511 QLocale lang (VBoxGlobal::languageId());
2512
2513 QStringList filesList = docDir.entryList();
2514 QString licenseFile;
2515 /* First try to find a localized version of the license file. */
2516 double versionNumber = findLicenseFile (filesList, QRegExp (QString ("License-([\\d\\.]+)-%1.html").arg (lang.name())), licenseFile);
2517 /* If there wasn't a localized version of the currently selected language,
2518 * search for the generic one. */
2519 if (versionNumber == 0)
2520 versionNumber = findLicenseFile (filesList, QRegExp ("License-([\\d\\.]+).html"), licenseFile);
2521 /* Check the version again. */
2522 if (!versionNumber)
2523 {
2524 vboxProblem().cannotFindLicenseFiles (path);
2525 return false;
2526 }
2527
2528 /* compose the latest license file full path */
2529 QString latestVersion = QString::number (versionNumber);
2530 QString latestFilePath = docDir.absoluteFilePath (licenseFile);
2531
2532 /* check for the agreed license version */
2533 QString licenseAgreed = virtualBox().GetExtraData (VBoxDefs::GUI_LicenseKey);
2534 if (licenseAgreed == latestVersion)
2535 return true;
2536
2537 VBoxLicenseViewer licenseDialog (latestFilePath);
2538 bool result = licenseDialog.exec() == QDialog::Accepted;
2539 if (result)
2540 virtualBox().SetExtraData (VBoxDefs::GUI_LicenseKey, latestVersion);
2541 return result;
2542}
2543#endif /* defined(Q_WS_X11) && !defined(VBOX_OSE) */
2544
2545/**
2546 * Checks if any of the settings files were auto-converted and informs the user
2547 * if so. Returns @c false if the user select to exit the application.
2548 */
2549bool VBoxGlobal::checkForAutoConvertedSettings()
2550{
2551 QString formatVersion = mVBox.GetSettingsFormatVersion();
2552
2553 bool isGlobalConverted = false;
2554 QList <CMachine> machines;
2555 QString fileList;
2556 QString version;
2557
2558 CMachineVector vec = mVBox.GetMachines2();
2559 for (CMachineVector::ConstIterator m = vec.begin();
2560 m != vec.end(); ++ m)
2561 {
2562 if (!m->GetAccessible())
2563 continue;
2564
2565 version = m->GetSettingsFileVersion();
2566 if (version != formatVersion)
2567 {
2568 machines.append (*m);
2569 fileList += QString ("<tr><td><nobr>%1</nobr></td><td>&nbsp;&nbsp;</td>"
2570 "</td><td><nobr><i>%2</i></nobr></td></tr>")
2571 .arg (m->GetSettingsFilePath())
2572 .arg (version);
2573 }
2574 }
2575
2576 version = mVBox.GetSettingsFileVersion();
2577 if (version != formatVersion)
2578 {
2579 isGlobalConverted = true;
2580 fileList += QString ("<tr><td><nobr>%1</nobr></td><td>&nbsp;&nbsp;</td>"
2581 "</td><td><nobr><i>%2</i></nobr></td></tr>")
2582 .arg (mVBox.GetSettingsFilePath())
2583 .arg (version);
2584 }
2585
2586 if (!fileList.isNull())
2587 {
2588 fileList = QString ("<table cellspacing=0 cellpadding=0>%1</table>")
2589 .arg (fileList);
2590
2591 int rc = vboxProblem()
2592 .warnAboutAutoConvertedSettings (formatVersion, fileList);
2593
2594 if (rc == QIMessageBox::Cancel)
2595 return false;
2596
2597 Assert (rc == QIMessageBox::No || rc == QIMessageBox::Yes);
2598
2599 /* backup (optionally) and save all settings files
2600 * (QIMessageBox::No = Backup, QIMessageBox::Yes = Save) */
2601
2602 foreach (CMachine m, machines)
2603 {
2604 CSession session = openSession (m.GetId());
2605 if (!session.isNull())
2606 {
2607 CMachine sm = session.GetMachine();
2608 if (rc == QIMessageBox::No)
2609 sm.SaveSettingsWithBackup();
2610 else
2611 sm.SaveSettings();
2612
2613 if (!sm.isOk())
2614 vboxProblem().cannotSaveMachineSettings (sm);
2615 session.Close();
2616 }
2617 }
2618
2619 if (isGlobalConverted)
2620 {
2621 if (rc == QIMessageBox::No)
2622 mVBox.SaveSettingsWithBackup();
2623 else
2624 mVBox.SaveSettings();
2625
2626 if (!mVBox.isOk())
2627 vboxProblem().cannotSaveGlobalSettings (mVBox);
2628 }
2629 }
2630
2631 return true;
2632}
2633
2634/**
2635 * Opens a direct session for a machine with the given ID.
2636 * This method does user-friendly error handling (display error messages, etc.).
2637 * and returns a null CSession object in case of any error.
2638 * If this method succeeds, don't forget to close the returned session when
2639 * it is no more necessary.
2640 *
2641 * @param aId Machine ID.
2642 * @param aExisting @c true to open an existing session with the machine
2643 * which is already running, @c false to open a new direct
2644 * session.
2645 */
2646CSession VBoxGlobal::openSession (const QUuid &aId, bool aExisting /* = false */)
2647{
2648 CSession session;
2649 session.createInstance (CLSID_Session);
2650 if (session.isNull())
2651 {
2652 vboxProblem().cannotOpenSession (session);
2653 return session;
2654 }
2655
2656 if (aExisting)
2657 mVBox.OpenExistingSession (session, aId);
2658 else
2659 {
2660 mVBox.OpenSession (session, aId);
2661 CMachine machine = session.GetMachine ();
2662 /* Make sure that the language is in two letter code.
2663 * Note: if languageId() returns an empty string lang.name() will
2664 * return "C" which is an valid language code. */
2665 QLocale lang (VBoxGlobal::languageId());
2666 machine.SetGuestPropertyValue ("/VirtualBox/HostInfo/GUI/LanguageID", lang.name());
2667 }
2668
2669 if (!mVBox.isOk())
2670 {
2671 CMachine machine = CVirtualBox (mVBox).GetMachine (aId);
2672 vboxProblem().cannotOpenSession (mVBox, machine);
2673 session.detach();
2674 }
2675
2676 return session;
2677}
2678
2679/**
2680 * Starts a machine with the given ID.
2681 */
2682bool VBoxGlobal::startMachine (const QUuid &id)
2683{
2684 AssertReturn (mValid, false);
2685
2686 CSession session = vboxGlobal().openSession (id);
2687 if (session.isNull())
2688 return false;
2689
2690 return consoleWnd().openView (session);
2691}
2692
2693/**
2694 * Appends the given list of hard disks and all their children to the media
2695 * list. To be called only from VBoxGlobal::startEnumeratingMedia().
2696 */
2697static
2698void AddHardDisksToList (const CHardDisk2Vector &aVector,
2699 VBoxMediaList &aList,
2700 VBoxMediaList::iterator aWhere,
2701 VBoxMedium *aParent = 0)
2702{
2703 VBoxMediaList::iterator first = aWhere;
2704
2705 /* First pass: Add siblings sorted */
2706 for (CHardDisk2Vector::ConstIterator it = aVector.begin();
2707 it != aVector.end(); ++ it)
2708 {
2709 CMedium cmedium (*it);
2710 VBoxMedium medium (cmedium, VBoxDefs::MediaType_HardDisk, aParent);
2711
2712 /* Search for a proper alphabetic position */
2713 VBoxMediaList::iterator jt = first;
2714 for (; jt != aWhere; ++ jt)
2715 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
2716 break;
2717
2718 aList.insert (jt, medium);
2719
2720 /* Adjust the first item if inserted before it */
2721 if (jt == first)
2722 -- first;
2723 }
2724
2725 /* Second pass: Add children */
2726 for (VBoxMediaList::iterator it = first; it != aWhere;)
2727 {
2728 CHardDisk2Vector children = (*it).hardDisk().GetChildren();
2729 VBoxMedium *parent = &(*it);
2730
2731 ++ it; /* go to the next sibling before inserting children */
2732 AddHardDisksToList (children, aList, it, parent);
2733 }
2734}
2735
2736/**
2737 * Starts a thread that asynchronously enumerates all currently registered
2738 * media.
2739 *
2740 * Before the enumeration is started, the current media list (a list returned by
2741 * #currentMediaList()) is populated with all registered media and the
2742 * #mediumEnumStarted() signal is emitted. The enumeration thread then walks this
2743 * list, checks for media acessiblity and emits #mediumEnumerated() signals of
2744 * each checked medium. When all media are checked, the enumeration thread is
2745 * stopped and the #mediumEnumFinished() signal is emitted.
2746 *
2747 * If the enumeration is already in progress, no new thread is started.
2748 *
2749 * The media list returned by #currentMediaList() is always sorted
2750 * alphabetically by the location attribute and comes in the following order:
2751 * <ol>
2752 * <li>All hard disks. If a hard disk has children, these children
2753 * (alphabetically sorted) immediately follow their parent and terefore
2754 * appear before its next sibling hard disk.</li>
2755 * <li>All CD/DVD images.</li>
2756 * <li>All Floppy images.</li>
2757 * </ol>
2758 *
2759 * Note that #mediumEnumerated() signals are emitted in the same order as
2760 * described above.
2761 *
2762 * @sa #currentMediaList()
2763 * @sa #isMediaEnumerationStarted()
2764 */
2765void VBoxGlobal::startEnumeratingMedia()
2766{
2767 AssertReturnVoid (mValid);
2768
2769 /* check if already started but not yet finished */
2770 if (mMediaEnumThread != NULL)
2771 return;
2772
2773 /* ignore the request during application termination */
2774 if (sVBoxGlobalInCleanup)
2775 return;
2776
2777 /* composes a list of all currently known media & their children */
2778 mMediaList.clear();
2779 {
2780 AddHardDisksToList (mVBox.GetHardDisks2(), mMediaList, mMediaList.end());
2781 }
2782 {
2783 VBoxMediaList::iterator first = mMediaList.end();
2784
2785 CDVDImage2Vector vec = mVBox.GetDVDImages();
2786 for (CDVDImage2Vector::ConstIterator it = vec.begin();
2787 it != vec.end(); ++ it)
2788 {
2789 CMedium cmedium (*it);
2790 VBoxMedium medium (cmedium, VBoxDefs::MediaType_DVD);
2791
2792 /* Search for a proper alphabetic position */
2793 VBoxMediaList::iterator jt = first;
2794 for (; jt != mMediaList.end(); ++ jt)
2795 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
2796 break;
2797
2798 mMediaList.insert (jt, medium);
2799
2800 /* Adjust the first item if inserted before it */
2801 if (jt == first)
2802 -- first;
2803 }
2804 }
2805 {
2806 VBoxMediaList::iterator first = mMediaList.end();
2807
2808 CFloppyImage2Vector vec = mVBox.GetFloppyImages();
2809 for (CFloppyImage2Vector::ConstIterator it = vec.begin();
2810 it != vec.end(); ++ it)
2811 {
2812 CMedium cmedium (*it);
2813 VBoxMedium medium (cmedium, VBoxDefs::MediaType_Floppy);
2814
2815 /* Search for a proper alphabetic position */
2816 VBoxMediaList::iterator jt = first;
2817 for (; jt != mMediaList.end(); ++ jt)
2818 if ((*jt).name().localeAwareCompare (medium.name()) > 0)
2819 break;
2820
2821 mMediaList.insert (jt, medium);
2822
2823 /* Adjust the first item if inserted before it */
2824 if (jt == first)
2825 -- first;
2826 }
2827 }
2828 mCurrentMediumIterator = mMediaList.begin();
2829
2830 /* enumeration thread class */
2831 class MediaEnumThread : public QThread
2832 {
2833 public:
2834
2835 MediaEnumThread (const VBoxMediaList &aList) : mList (aList) {}
2836
2837 virtual void run()
2838 {
2839 LogFlow (("MediaEnumThread started.\n"));
2840 COMBase::InitializeCOM();
2841
2842 CVirtualBox mVBox = vboxGlobal().virtualBox();
2843 QObject *self = &vboxGlobal();
2844
2845 /* Enumerate the list */
2846 int index = 0;
2847 VBoxMediaList::const_iterator it;
2848 for (it = mList.begin();
2849 it != mList.end() && !sVBoxGlobalInCleanup;
2850 ++ it, ++ index)
2851 {
2852 VBoxMedium medium = *it;
2853 medium.blockAndQueryState();
2854 QApplication::postEvent (self, new VBoxMediaEnumEvent (medium));
2855 }
2856
2857 /* Post the end-of-enumeration event */
2858 if (!sVBoxGlobalInCleanup)
2859 QApplication::postEvent (self, new VBoxMediaEnumEvent());
2860
2861 COMBase::CleanupCOM();
2862 LogFlow (("MediaEnumThread finished.\n"));
2863 }
2864
2865 private:
2866
2867 const VBoxMediaList &mList;
2868 };
2869
2870 mMediaEnumThread = new MediaEnumThread (mMediaList);
2871 AssertReturnVoid (mMediaEnumThread);
2872
2873 /* emit mediumEnumStarted() after we set mMediaEnumThread to != NULL
2874 * to cause isMediaEnumerationStarted() to return TRUE from slots */
2875 emit mediumEnumStarted();
2876
2877 mMediaEnumThread->start();
2878}
2879
2880/**
2881 * Adds a new medium to the current media list and emits the #mediumAdded()
2882 * signal.
2883 *
2884 * @sa #currentMediaList()
2885 */
2886void VBoxGlobal::addMedium (const VBoxMedium &aMedium)
2887{
2888 /* Note that we maitain the same order here as #startEnumeratingMedia() */
2889
2890 VBoxMediaList::iterator it = mMediaList.begin();
2891
2892 if (aMedium.type() == VBoxDefs::MediaType_HardDisk)
2893 {
2894 VBoxMediaList::iterator parent = mMediaList.end();
2895
2896 for (; it != mMediaList.end(); ++ it)
2897 {
2898 if ((*it).type() != VBoxDefs::MediaType_HardDisk)
2899 break;
2900
2901 if (aMedium.parent() != NULL && parent == mMediaList.end())
2902 {
2903 if (&*it == aMedium.parent())
2904 parent = it;
2905 }
2906 else
2907 {
2908 /* break if met a parent's sibling (will insert before it) */
2909 if (aMedium.parent() != NULL &&
2910 (*it).parent() == (*parent).parent())
2911 break;
2912
2913 /* compare to aMedium's siblings */
2914 if ((*it).parent() == aMedium.parent() &&
2915 (*it).name().localeAwareCompare (aMedium.name()) > 0)
2916 break;
2917 }
2918 }
2919
2920 AssertReturnVoid (aMedium.parent() == NULL || parent != mMediaList.end());
2921 }
2922 else
2923 {
2924 for (; it != mMediaList.end(); ++ it)
2925 {
2926 /* skip HardDisks that come first */
2927 if ((*it).type() == VBoxDefs::MediaType_HardDisk)
2928 continue;
2929
2930 /* skip DVD when inserting Floppy */
2931 if (aMedium.type() == VBoxDefs::MediaType_Floppy &&
2932 (*it).type() == VBoxDefs::MediaType_DVD)
2933 continue;
2934
2935 if ((*it).name().localeAwareCompare (aMedium.name()) > 0 ||
2936 (aMedium.type() == VBoxDefs::MediaType_DVD &&
2937 (*it).type() == VBoxDefs::MediaType_Floppy))
2938 break;
2939 }
2940 }
2941
2942 it = mMediaList.insert (it, aMedium);
2943
2944 emit mediumAdded (*it);
2945}
2946
2947/**
2948 * Updates the medium in the current media list and emits the #mediumUpdated()
2949 * signal.
2950 *
2951 * @sa #currentMediaList()
2952 */
2953void VBoxGlobal::updateMedium (const VBoxMedium &aMedium)
2954{
2955 VBoxMediaList::Iterator it;
2956 for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2957 if ((*it).id() == aMedium.id())
2958 break;
2959
2960 AssertReturnVoid (it != mMediaList.end());
2961
2962 if (&*it != &aMedium)
2963 *it = aMedium;
2964
2965 emit mediumUpdated (*it);
2966}
2967
2968/**
2969 * Removes the medium from the current media list and emits the #mediumRemoved()
2970 * signal.
2971 *
2972 * @sa #currentMediaList()
2973 */
2974void VBoxGlobal::removeMedium (VBoxDefs::MediaType aType, const QUuid &aId)
2975{
2976 VBoxMediaList::Iterator it;
2977 for (it = mMediaList.begin(); it != mMediaList.end(); ++ it)
2978 if ((*it).id() == aId)
2979 break;
2980
2981 AssertReturnVoid (it != mMediaList.end());
2982
2983#if DEBUG
2984 /* sanity: must be no children */
2985 {
2986 VBoxMediaList::Iterator jt = it;
2987 ++ jt;
2988 AssertReturnVoid (jt == mMediaList.end() || (*jt).parent() != &*it);
2989 }
2990#endif
2991
2992 VBoxMedium *parent = (*it).parent();
2993
2994 /* remove the medium from the list to keep it in sync with the server "for
2995 * free" when the medium is deleted from one of our UIs */
2996 mMediaList.erase (it);
2997
2998 emit mediumRemoved (aType, aId);
2999
3000 /* also emit the parent update signal because some attributes like
3001 * isReadOnly() may have been changed after child removal */
3002 if (parent != NULL)
3003 {
3004 parent->refresh();
3005 emit mediumUpdated (*parent);
3006 }
3007}
3008
3009/**
3010 * Searches for a VBoxMedum object representing the given COM medium object.
3011 *
3012 * @return true if found and false otherwise.
3013 */
3014bool VBoxGlobal::findMedium (const CMedium &aObj, VBoxMedium &aMedium) const
3015{
3016 for (VBoxMediaList::ConstIterator it = mMediaList.begin();
3017 it != mMediaList.end(); ++ it)
3018 {
3019 if ((*it).medium() == aObj)
3020 {
3021 aMedium = (*it);
3022 return true;
3023 }
3024 }
3025
3026 return false;
3027}
3028
3029/**
3030 * Native language name of the currently installed translation.
3031 * Returns "English" if no translation is installed
3032 * or if the translation file is invalid.
3033 */
3034QString VBoxGlobal::languageName() const
3035{
3036
3037 return qApp->translate ("@@@", "English",
3038 "Native language name");
3039}
3040
3041/**
3042 * Native language country name of the currently installed translation.
3043 * Returns "--" if no translation is installed or if the translation file is
3044 * invalid, or if the language is independent on the country.
3045 */
3046QString VBoxGlobal::languageCountry() const
3047{
3048 return qApp->translate ("@@@", "--",
3049 "Native language country name "
3050 "(empty if this language is for all countries)");
3051}
3052
3053/**
3054 * Language name of the currently installed translation, in English.
3055 * Returns "English" if no translation is installed
3056 * or if the translation file is invalid.
3057 */
3058QString VBoxGlobal::languageNameEnglish() const
3059{
3060
3061 return qApp->translate ("@@@", "English",
3062 "Language name, in English");
3063}
3064
3065/**
3066 * Language country name of the currently installed translation, in English.
3067 * Returns "--" if no translation is installed or if the translation file is
3068 * invalid, or if the language is independent on the country.
3069 */
3070QString VBoxGlobal::languageCountryEnglish() const
3071{
3072 return qApp->translate ("@@@", "--",
3073 "Language country name, in English "
3074 "(empty if native country name is empty)");
3075}
3076
3077/**
3078 * Comma-separated list of authors of the currently installed translation.
3079 * Returns "Sun Microsystems, Inc." if no translation is installed or if the
3080 * translation file is invalid, or if the translation is supplied by Sun
3081 * Microsystems, inc.
3082 */
3083QString VBoxGlobal::languageTranslators() const
3084{
3085 return qApp->translate ("@@@", "Sun Microsystems, Inc.",
3086 "Comma-separated list of translators");
3087}
3088
3089/**
3090 * Changes the language of all global string constants according to the
3091 * currently installed translations tables.
3092 */
3093void VBoxGlobal::retranslateUi()
3094{
3095 machineStates [KMachineState_PoweredOff] = tr ("Powered Off", "MachineState");
3096 machineStates [KMachineState_Saved] = tr ("Saved", "MachineState");
3097 machineStates [KMachineState_Aborted] = tr ("Aborted", "MachineState");
3098 machineStates [KMachineState_Running] = tr ("Running", "MachineState");
3099 machineStates [KMachineState_Paused] = tr ("Paused", "MachineState");
3100 machineStates [KMachineState_Stuck] = tr ("Stuck", "MachineState");
3101 machineStates [KMachineState_Starting] = tr ("Starting", "MachineState");
3102 machineStates [KMachineState_Stopping] = tr ("Stopping", "MachineState");
3103 machineStates [KMachineState_Saving] = tr ("Saving", "MachineState");
3104 machineStates [KMachineState_Restoring] = tr ("Restoring", "MachineState");
3105 machineStates [KMachineState_Discarding] = tr ("Discarding", "MachineState");
3106 machineStates [KMachineState_SettingUp] = tr ("Setting Up", "MachineState");
3107
3108 sessionStates [KSessionState_Closed] = tr ("Closed", "SessionState");
3109 sessionStates [KSessionState_Open] = tr ("Open", "SessionState");
3110 sessionStates [KSessionState_Spawning] = tr ("Spawning", "SessionState");
3111 sessionStates [KSessionState_Closing] = tr ("Closing", "SessionState");
3112
3113 deviceTypes [KDeviceType_Null] = tr ("None", "DeviceType");
3114 deviceTypes [KDeviceType_Floppy] = tr ("Floppy", "DeviceType");
3115 deviceTypes [KDeviceType_DVD] = tr ("CD/DVD-ROM", "DeviceType");
3116 deviceTypes [KDeviceType_HardDisk] = tr ("Hard Disk", "DeviceType");
3117 deviceTypes [KDeviceType_Network] = tr ("Network", "DeviceType");
3118 deviceTypes [KDeviceType_USB] = tr ("USB", "DeviceType");
3119 deviceTypes [KDeviceType_SharedFolder] = tr ("Shared Folder", "DeviceType");
3120
3121 storageBuses [KStorageBus_IDE] =
3122 tr ("IDE", "StorageBus");
3123 storageBuses [KStorageBus_SATA] =
3124 tr ("SATA", "StorageBus");
3125
3126 Assert (storageBusChannels.count() == 3);
3127 storageBusChannels [0] =
3128 tr ("Primary", "StorageBusChannel");
3129 storageBusChannels [1] =
3130 tr ("Secondary", "StorageBusChannel");
3131 storageBusChannels [2] =
3132 tr ("Port %1", "StorageBusChannel");
3133
3134 Assert (storageBusDevices.count() == 2);
3135 storageBusDevices [0] = tr ("Master", "StorageBusDevice");
3136 storageBusDevices [1] = tr ("Slave", "StorageBusDevice");
3137
3138 diskTypes [KHardDiskType_Normal] =
3139 tr ("Normal", "DiskType");
3140 diskTypes [KHardDiskType_Immutable] =
3141 tr ("Immutable", "DiskType");
3142 diskTypes [KHardDiskType_Writethrough] =
3143 tr ("Writethrough", "DiskType");
3144 diskTypes_Differencing =
3145 tr ("Differencing", "DiskType");
3146
3147 vrdpAuthTypes [KVRDPAuthType_Null] =
3148 tr ("Null", "VRDPAuthType");
3149 vrdpAuthTypes [KVRDPAuthType_External] =
3150 tr ("External", "VRDPAuthType");
3151 vrdpAuthTypes [KVRDPAuthType_Guest] =
3152 tr ("Guest", "VRDPAuthType");
3153
3154 portModeTypes [KPortMode_Disconnected] =
3155 tr ("Disconnected", "PortMode");
3156 portModeTypes [KPortMode_HostPipe] =
3157 tr ("Host Pipe", "PortMode");
3158 portModeTypes [KPortMode_HostDevice] =
3159 tr ("Host Device", "PortMode");
3160
3161 usbFilterActionTypes [KUSBDeviceFilterAction_Ignore] =
3162 tr ("Ignore", "USBFilterActionType");
3163 usbFilterActionTypes [KUSBDeviceFilterAction_Hold] =
3164 tr ("Hold", "USBFilterActionType");
3165
3166 audioDriverTypes [KAudioDriverType_Null] =
3167 tr ("Null Audio Driver", "AudioDriverType");
3168 audioDriverTypes [KAudioDriverType_WinMM] =
3169 tr ("Windows Multimedia", "AudioDriverType");
3170 audioDriverTypes [KAudioDriverType_SolAudio] =
3171 tr ("Solaris Audio", "AudioDriverType");
3172 audioDriverTypes [KAudioDriverType_OSS] =
3173 tr ("OSS Audio Driver", "AudioDriverType");
3174 audioDriverTypes [KAudioDriverType_ALSA] =
3175 tr ("ALSA Audio Driver", "AudioDriverType");
3176 audioDriverTypes [KAudioDriverType_DirectSound] =
3177 tr ("Windows DirectSound", "AudioDriverType");
3178 audioDriverTypes [KAudioDriverType_CoreAudio] =
3179 tr ("CoreAudio", "AudioDriverType");
3180 audioDriverTypes [KAudioDriverType_Pulse] =
3181 tr ("PulseAudio", "AudioDriverType");
3182
3183 audioControllerTypes [KAudioControllerType_AC97] =
3184 tr ("ICH AC97", "AudioControllerType");
3185 audioControllerTypes [KAudioControllerType_SB16] =
3186 tr ("SoundBlaster 16", "AudioControllerType");
3187
3188 networkAdapterTypes [KNetworkAdapterType_Am79C970A] =
3189 tr ("PCnet-PCI II (Am79C970A)", "NetworkAdapterType");
3190 networkAdapterTypes [KNetworkAdapterType_Am79C973] =
3191 tr ("PCnet-FAST III (Am79C973)", "NetworkAdapterType");
3192 networkAdapterTypes [KNetworkAdapterType_I82540EM] =
3193 tr ("Intel PRO/1000 MT Desktop (82540EM)", "NetworkAdapterType");
3194 networkAdapterTypes [KNetworkAdapterType_I82543GC] =
3195 tr ("Intel PRO/1000 T Server (82543GC)", "NetworkAdapterType");
3196
3197 networkAttachmentTypes [KNetworkAttachmentType_Null] =
3198 tr ("Not attached", "NetworkAttachmentType");
3199 networkAttachmentTypes [KNetworkAttachmentType_NAT] =
3200 tr ("NAT", "NetworkAttachmentType");
3201 networkAttachmentTypes [KNetworkAttachmentType_HostInterface] =
3202 tr ("Host Interface", "NetworkAttachmentType");
3203 networkAttachmentTypes [KNetworkAttachmentType_Internal] =
3204 tr ("Internal Network", "NetworkAttachmentType");
3205
3206 clipboardTypes [KClipboardMode_Disabled] =
3207 tr ("Disabled", "ClipboardType");
3208 clipboardTypes [KClipboardMode_HostToGuest] =
3209 tr ("Host To Guest", "ClipboardType");
3210 clipboardTypes [KClipboardMode_GuestToHost] =
3211 tr ("Guest To Host", "ClipboardType");
3212 clipboardTypes [KClipboardMode_Bidirectional] =
3213 tr ("Bidirectional", "ClipboardType");
3214
3215 ideControllerTypes [KIDEControllerType_PIIX3] =
3216 tr ("PIIX3", "IDEControllerType");
3217 ideControllerTypes [KIDEControllerType_PIIX4] =
3218 tr ("PIIX4", "IDEControllerType");
3219
3220 USBDeviceStates [KUSBDeviceState_NotSupported] =
3221 tr ("Not supported", "USBDeviceState");
3222 USBDeviceStates [KUSBDeviceState_Unavailable] =
3223 tr ("Unavailable", "USBDeviceState");
3224 USBDeviceStates [KUSBDeviceState_Busy] =
3225 tr ("Busy", "USBDeviceState");
3226 USBDeviceStates [KUSBDeviceState_Available] =
3227 tr ("Available", "USBDeviceState");
3228 USBDeviceStates [KUSBDeviceState_Held] =
3229 tr ("Held", "USBDeviceState");
3230 USBDeviceStates [KUSBDeviceState_Captured] =
3231 tr ("Captured", "USBDeviceState");
3232
3233 mUserDefinedPortName = tr ("User-defined", "serial port");
3234
3235 mWarningIcon = standardIcon (QStyle::SP_MessageBoxWarning, 0).pixmap (16, 16);
3236 Assert (!mWarningIcon.isNull());
3237
3238 mErrorIcon = standardIcon (QStyle::SP_MessageBoxCritical, 0).pixmap (16, 16);
3239 Assert (!mErrorIcon.isNull());
3240
3241 detailReportTemplatesReady = false;
3242
3243#if defined (Q_WS_PM) || defined (Q_WS_X11)
3244 /* As PM and X11 do not (to my knowledge) have functionality for providing
3245 * human readable key names, we keep a table of them, which must be
3246 * updated when the language is changed. */
3247 QIHotKeyEdit::retranslateUi();
3248#endif
3249}
3250
3251// public static stuff
3252////////////////////////////////////////////////////////////////////////////////
3253
3254/* static */
3255bool VBoxGlobal::isDOSType (const QString &aOSTypeId)
3256{
3257 if (aOSTypeId.left (3) == "dos" ||
3258 aOSTypeId.left (3) == "win" ||
3259 aOSTypeId.left (3) == "os2")
3260 return true;
3261
3262 return false;
3263}
3264
3265/**
3266 * Sets the QLabel background and frame colors according tho the pixmap
3267 * contents. The bottom right pixel of the label pixmap defines the
3268 * background color of the label, the top right pixel defines the color of
3269 * the one-pixel frame around it. This function also sets the alignment of
3270 * the pixmap to AlignVTop (to correspond to the color choosing logic).
3271 *
3272 * This method is useful to provide nice scaling of pixmal labels without
3273 * scaling pixmaps themselves. To see th eeffect, the size policy of the
3274 * label in the corresponding direction (vertical, for now) should be set to
3275 * something like MinimumExpanding.
3276 *
3277 * @todo Parametrize corners to select pixels from and set the alignment
3278 * accordingly.
3279 */
3280/* static */
3281void VBoxGlobal::adoptLabelPixmap (QLabel *aLabel)
3282{
3283 AssertReturnVoid (aLabel);
3284
3285 aLabel->setAlignment (Qt::AlignTop);
3286 aLabel->setFrameShape (QFrame::Box);
3287 aLabel->setFrameShadow (QFrame::Plain);
3288
3289 const QPixmap *pix = aLabel->pixmap();
3290 QImage img = pix->toImage();
3291 QRgb rgbBack = img.pixel (img.width() - 1, img.height() - 1);
3292 QRgb rgbFrame = img.pixel (img.width() - 1, 0);
3293
3294 QPalette pal = aLabel->palette();
3295 pal.setColor (QPalette::Window, rgbBack);
3296 pal.setColor (QPalette::WindowText, rgbFrame);
3297 aLabel->setPalette (pal);
3298}
3299
3300extern const char *gVBoxLangSubDir = "/nls";
3301extern const char *gVBoxLangFileBase = "VirtualBox_";
3302extern const char *gVBoxLangFileExt = ".qm";
3303extern const char *gVBoxLangIDRegExp = "(([a-z]{2})(?:_([A-Z]{2}))?)|(C)";
3304extern const char *gVBoxBuiltInLangName = "C";
3305
3306class VBoxTranslator : public QTranslator
3307{
3308public:
3309
3310 VBoxTranslator (QObject *aParent = 0)
3311 : QTranslator (aParent) {}
3312
3313 bool loadFile (const QString &aFileName)
3314 {
3315 QFile file (aFileName);
3316 if (!file.open (QIODevice::ReadOnly))
3317 return false;
3318 mData = file.readAll();
3319 return load ((uchar*) mData.data(), mData.size());
3320 }
3321
3322private:
3323
3324 QByteArray mData;
3325};
3326
3327static VBoxTranslator *sTranslator = 0;
3328static QString sLoadedLangId = gVBoxBuiltInLangName;
3329
3330/**
3331 * Returns the loaded (active) language ID.
3332 * Note that it may not match with VBoxGlobalSettings::languageId() if the
3333 * specified language cannot be loaded.
3334 * If the built-in language is active, this method returns "C".
3335 *
3336 * @note "C" is treated as the built-in language for simplicity -- the C
3337 * locale is used in unix environments as a fallback when the requested
3338 * locale is invalid. This way we don't need to process both the "built_in"
3339 * language and the "C" language (which is a valid environment setting)
3340 * separately.
3341 */
3342/* static */
3343QString VBoxGlobal::languageId()
3344{
3345 return sLoadedLangId;
3346}
3347
3348/**
3349 * Loads the language by language ID.
3350 *
3351 * @param aLangId Language ID in in form of xx_YY. QString::null means the
3352 * system default language.
3353 */
3354/* static */
3355void VBoxGlobal::loadLanguage (const QString &aLangId)
3356{
3357 QString langId = aLangId.isNull() ?
3358 VBoxGlobal::systemLanguageId() : aLangId;
3359 QString languageFileName;
3360 QString selectedLangId = gVBoxBuiltInLangName;
3361
3362 char szNlsPath[RTPATH_MAX];
3363 int rc;
3364
3365 rc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
3366 AssertRC (rc);
3367
3368 QString nlsPath = QString(szNlsPath) + gVBoxLangSubDir;
3369 QDir nlsDir (nlsPath);
3370
3371 Assert (!langId.isEmpty());
3372 if (!langId.isEmpty() && langId != gVBoxBuiltInLangName)
3373 {
3374 QRegExp regExp (gVBoxLangIDRegExp);
3375 int pos = regExp.indexIn (langId);
3376 /* the language ID should match the regexp completely */
3377 AssertReturnVoid (pos == 0);
3378
3379 QString lang = regExp.cap (2);
3380
3381 if (nlsDir.exists (gVBoxLangFileBase + langId + gVBoxLangFileExt))
3382 {
3383 languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + langId +
3384 gVBoxLangFileExt);
3385 selectedLangId = langId;
3386 }
3387 else if (nlsDir.exists (gVBoxLangFileBase + lang + gVBoxLangFileExt))
3388 {
3389 languageFileName = nlsDir.absoluteFilePath (gVBoxLangFileBase + lang +
3390 gVBoxLangFileExt);
3391 selectedLangId = lang;
3392 }
3393 else
3394 {
3395 /* Never complain when the default language is requested. In any
3396 * case, if no explicit language file exists, we will simply
3397 * fall-back to English (built-in). */
3398 if (!aLangId.isNull())
3399 vboxProblem().cannotFindLanguage (langId, nlsPath);
3400 /* selectedLangId remains built-in here */
3401 AssertReturnVoid (selectedLangId == gVBoxBuiltInLangName);
3402 }
3403 }
3404
3405 /* delete the old translator if there is one */
3406 if (sTranslator)
3407 {
3408 /* QTranslator destructor will call qApp->removeTranslator() for
3409 * us. It will also delete all its child translations we attach to it
3410 * below, so we don't have to care about them specially. */
3411 delete sTranslator;
3412 }
3413
3414 /* load new language files */
3415 sTranslator = new VBoxTranslator (qApp);
3416 Assert (sTranslator);
3417 bool loadOk = true;
3418 if (sTranslator)
3419 {
3420 if (selectedLangId != gVBoxBuiltInLangName)
3421 {
3422 Assert (!languageFileName.isNull());
3423 loadOk = sTranslator->loadFile (languageFileName);
3424 }
3425 /* we install the translator in any case: on failure, this will
3426 * activate an empty translator that will give us English
3427 * (built-in) */
3428 qApp->installTranslator (sTranslator);
3429 }
3430 else
3431 loadOk = false;
3432
3433 if (loadOk)
3434 sLoadedLangId = selectedLangId;
3435 else
3436 {
3437 vboxProblem().cannotLoadLanguage (languageFileName);
3438 sLoadedLangId = gVBoxBuiltInLangName;
3439 }
3440
3441 /* Try to load the corresponding Qt translation */
3442 if (sLoadedLangId != gVBoxBuiltInLangName)
3443 {
3444#ifdef Q_OS_UNIX
3445 /* We use system installations of Qt on Linux systems, so first, try
3446 * to load the Qt translation from the system location. */
3447 languageFileName = QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" +
3448 sLoadedLangId + gVBoxLangFileExt;
3449 QTranslator *qtSysTr = new QTranslator (sTranslator);
3450 Assert (qtSysTr);
3451 if (qtSysTr && qtSysTr->load (languageFileName))
3452 qApp->installTranslator (qtSysTr);
3453 /* Note that the Qt translation supplied by Sun is always loaded
3454 * afterwards to make sure it will take precedence over the system
3455 * translation (it may contain more decent variants of translation
3456 * that better correspond to VirtualBox UI). We need to load both
3457 * because a newer version of Qt may be installed on the user computer
3458 * and the Sun version may not fully support it. We don't do it on
3459 * Win32 because we supply a Qt library there and therefore the
3460 * Sun translation is always the best one. */
3461#endif
3462 languageFileName = nlsDir.absoluteFilePath (QString ("qt_") +
3463 sLoadedLangId +
3464 gVBoxLangFileExt);
3465 QTranslator *qtTr = new QTranslator (sTranslator);
3466 Assert (qtTr);
3467 if (qtTr && (loadOk = qtTr->load (languageFileName)))
3468 qApp->installTranslator (qtTr);
3469 /* The below message doesn't fit 100% (because it's an additonal
3470 * language and the main one won't be reset to built-in on failure)
3471 * but the load failure is so rare here that it's not worth a separate
3472 * message (but still, having something is better than having none) */
3473 if (!loadOk && !aLangId.isNull())
3474 vboxProblem().cannotLoadLanguage (languageFileName);
3475 }
3476}
3477
3478QString VBoxGlobal::helpFile() const
3479{
3480#if defined (Q_WS_WIN32) || defined (Q_WS_X11)
3481 const QString name = "VirtualBox";
3482 const QString suffix = "chm";
3483#elif defined (Q_WS_MAC)
3484 const QString name = "UserManual";
3485 const QString suffix = "pdf";
3486#endif
3487 /* Where are the docs located? */
3488 char szDocsPath[RTPATH_MAX];
3489 int rc = RTPathAppDocs (szDocsPath, sizeof (szDocsPath));
3490 AssertRC (rc);
3491 /* Make sure that the language is in two letter code.
3492 * Note: if languageId() returns an empty string lang.name() will
3493 * return "C" which is an valid language code. */
3494 QLocale lang (VBoxGlobal::languageId());
3495
3496 /* Construct the path and the filename */
3497 QString manual = QString ("%1/%2_%3.%4").arg (szDocsPath)
3498 .arg (name)
3499 .arg (lang.name())
3500 .arg (suffix);
3501 /* Check if a help file with that name exists */
3502 QFileInfo fi (manual);
3503 if (fi.exists())
3504 return manual;
3505
3506 /* Fall back to the standard */
3507 manual = QString ("%1/%2.%4").arg (szDocsPath)
3508 .arg (name)
3509 .arg (suffix);
3510 return manual;
3511}
3512
3513/* static */
3514QIcon VBoxGlobal::iconSet (const char *aNormal,
3515 const char *aDisabled /* = NULL */,
3516 const char *aActive /* = NULL */)
3517{
3518 QIcon iconSet;
3519
3520 iconSet.addFile (aNormal, QSize(),
3521 QIcon::Normal);
3522 if (aDisabled != NULL)
3523 iconSet.addFile (aDisabled, QSize(),
3524 QIcon::Disabled);
3525 if (aActive != NULL)
3526 iconSet.addFile (aActive, QSize(),
3527 QIcon::Active);
3528 return iconSet;
3529}
3530
3531/* static */
3532QIcon VBoxGlobal::iconSetFull (const QSize &aNormalSize, const QSize &aSmallSize,
3533 const char *aNormal, const char *aSmallNormal,
3534 const char *aDisabled /* = NULL */,
3535 const char *aSmallDisabled /* = NULL */,
3536 const char *aActive /* = NULL */,
3537 const char *aSmallActive /* = NULL */)
3538{
3539 QIcon iconSet;
3540
3541 iconSet.addFile (aNormal, aNormalSize, QIcon::Normal);
3542 iconSet.addFile (aSmallNormal, aSmallSize, QIcon::Normal);
3543 if (aSmallDisabled != NULL)
3544 {
3545 iconSet.addFile (aDisabled, aNormalSize, QIcon::Disabled);
3546 iconSet.addFile (aSmallDisabled, aSmallSize, QIcon::Disabled);
3547 }
3548 if (aSmallActive != NULL)
3549 {
3550 iconSet.addFile (aActive, aNormalSize, QIcon::Active);
3551 iconSet.addFile (aSmallActive, aSmallSize, QIcon::Active);
3552 }
3553
3554 return iconSet;
3555}
3556
3557QIcon VBoxGlobal::standardIcon (QStyle::StandardPixmap aStandard, QWidget *aWidget /* = NULL */)
3558{
3559 QStyle *style = aWidget ? aWidget->style(): QApplication::style();
3560#ifdef Q_WS_MAC
3561 /* At least in Qt 4.3.4/4.4 RC1 SP_MessageBoxWarning is the application
3562 * icon. So change this to the critical icon. (Maybe this would be
3563 * fixed in a later Qt version) */
3564 if (aStandard == QStyle::SP_MessageBoxWarning)
3565 return style->standardIcon (QStyle::SP_MessageBoxCritical, 0, aWidget);
3566#endif /* Q_WS_MAC */
3567 return style->standardIcon (aStandard, 0, aWidget);
3568}
3569
3570/**
3571 * Replacement for QToolButton::setTextLabel() that handles the shortcut
3572 * letter (if it is present in the argument string) as if it were a setText()
3573 * call: the shortcut letter is used to automatically assign an "Alt+<letter>"
3574 * accelerator key sequence to the given tool button.
3575 *
3576 * @note This method preserves the icon set if it was assigned before. Only
3577 * the text label and the accelerator are changed.
3578 *
3579 * @param aToolButton Tool button to set the text label on.
3580 * @param aTextLabel Text label to set.
3581 */
3582/* static */
3583void VBoxGlobal::setTextLabel (QToolButton *aToolButton,
3584 const QString &aTextLabel)
3585{
3586 AssertReturnVoid (aToolButton != NULL);
3587
3588 /* remember the icon set as setText() will kill it */
3589 QIcon iset = aToolButton->icon();
3590 /* re-use the setText() method to detect and set the accelerator */
3591 aToolButton->setText (aTextLabel);
3592 QKeySequence accel = aToolButton->shortcut();
3593 aToolButton->setText (aTextLabel);
3594 aToolButton->setIcon (iset);
3595 /* set the accel last as setIconSet() would kill it */
3596 aToolButton->setShortcut (accel);
3597}
3598
3599/**
3600 * Ensures that the given rectangle \a aRect is fully contained within the
3601 * rectangle \a aBoundRect by moving \a aRect if necessary. If \a aRect is
3602 * larger than \a aBoundRect, its top left corner is simply aligned with the
3603 * top left corner of \a aRect and, if \a aCanResize is true, \a aRect is
3604 * shrinked to become fully visible.
3605 */
3606/* static */
3607QRect VBoxGlobal::normalizeGeometry (const QRect &aRect, const QRect &aBoundRect,
3608 bool aCanResize /* = true */)
3609{
3610 QRect fr = aRect;
3611
3612 /* make the bottom right corner visible */
3613 int rd = aBoundRect.right() - fr.right();
3614 int bd = aBoundRect.bottom() - fr.bottom();
3615 fr.translate (rd < 0 ? rd : 0, bd < 0 ? bd : 0);
3616
3617 /* ensure the top left corner is visible */
3618 int ld = fr.left() - aBoundRect.left();
3619 int td = fr.top() - aBoundRect.top();
3620 fr.translate (ld < 0 ? -ld : 0, td < 0 ? -td : 0);
3621
3622 if (aCanResize)
3623 {
3624 /* adjust the size to make the rectangle fully contained */
3625 rd = aBoundRect.right() - fr.right();
3626 bd = aBoundRect.bottom() - fr.bottom();
3627 if (rd < 0)
3628 fr.setRight (fr.right() + rd);
3629 if (bd < 0)
3630 fr.setBottom (fr.bottom() + bd);
3631 }
3632
3633 return fr;
3634}
3635
3636/**
3637 * Aligns the center of \a aWidget with the center of \a aRelative.
3638 *
3639 * If necessary, \a aWidget's position is adjusted to make it fully visible
3640 * within the available desktop area. If \a aWidget is bigger then this area,
3641 * it will also be resized unless \a aCanResize is false or there is an
3642 * inappropriate minimum size limit (in which case the top left corner will be
3643 * simply aligned with the top left corner of the available desktop area).
3644 *
3645 * \a aWidget must be a top-level widget. \a aRelative may be any widget, but
3646 * if it's not top-level itself, its top-level widget will be used for
3647 * calculations. \a aRelative can also be NULL, in which case \a aWidget will
3648 * be centered relative to the available desktop area.
3649 */
3650/* static */
3651void VBoxGlobal::centerWidget (QWidget *aWidget, QWidget *aRelative,
3652 bool aCanResize /* = true */)
3653{
3654 AssertReturnVoid (aWidget);
3655 AssertReturnVoid (aWidget->isTopLevel());
3656
3657 QRect deskGeo, parentGeo;
3658 QWidget *w = aRelative;
3659 if (w)
3660 {
3661 w = w->window();
3662 deskGeo = QApplication::desktop()->availableGeometry (w);
3663 parentGeo = w->frameGeometry();
3664 /* On X11/Gnome, geo/frameGeo.x() and y() are always 0 for top level
3665 * widgets with parents, what a shame. Use mapToGlobal() to workaround. */
3666 QPoint d = w->mapToGlobal (QPoint (0, 0));
3667 d.rx() -= w->geometry().x() - w->x();
3668 d.ry() -= w->geometry().y() - w->y();
3669 parentGeo.moveTopLeft (d);
3670 }
3671 else
3672 {
3673 deskGeo = QApplication::desktop()->availableGeometry();
3674 parentGeo = deskGeo;
3675 }
3676
3677 /* On X11, there is no way to determine frame geometry (including WM
3678 * decorations) before the widget is shown for the first time. Stupidly
3679 * enumerate other top level widgets to find the thickest frame. The code
3680 * is based on the idea taken from QDialog::adjustPositionInternal(). */
3681
3682 int extraw = 0, extrah = 0;
3683
3684 QWidgetList list = QApplication::topLevelWidgets();
3685 QListIterator<QWidget*> it (list);
3686 while ((extraw == 0 || extrah == 0) && it.hasNext())
3687 {
3688 int framew, frameh;
3689 QWidget *current = it.next();
3690 if (!current->isVisible())
3691 continue;
3692
3693 framew = current->frameGeometry().width() - current->width();
3694 frameh = current->frameGeometry().height() - current->height();
3695
3696 extraw = qMax (extraw, framew);
3697 extrah = qMax (extrah, frameh);
3698 }
3699
3700 /// @todo (r=dmik) not sure if we really need this
3701#if 0
3702 /* sanity check for decoration frames. With embedding, we
3703 * might get extraordinary values */
3704 if (extraw == 0 || extrah == 0 || extraw > 20 || extrah > 50)
3705 {
3706 extrah = 50;
3707 extraw = 20;
3708 }
3709#endif
3710
3711 /* On non-X11 platforms, the following would be enough instead of the
3712 * above workaround: */
3713 // QRect geo = frameGeometry();
3714 QRect geo = QRect (0, 0, aWidget->width() + extraw,
3715 aWidget->height() + extrah);
3716
3717 geo.moveCenter (QPoint (parentGeo.x() + (parentGeo.width() - 1) / 2,
3718 parentGeo.y() + (parentGeo.height() - 1) / 2));
3719
3720 /* ensure the widget is within the available desktop area */
3721 QRect newGeo = normalizeGeometry (geo, deskGeo, aCanResize);
3722
3723 aWidget->move (newGeo.topLeft());
3724
3725 if (aCanResize &&
3726 (geo.width() != newGeo.width() || geo.height() != newGeo.height()))
3727 aWidget->resize (newGeo.width() - extraw, newGeo.height() - extrah);
3728}
3729
3730/**
3731 * Returns the decimal separator for the current locale.
3732 */
3733/* static */
3734QChar VBoxGlobal::decimalSep()
3735{
3736 return QLocale::system().decimalPoint();
3737}
3738
3739/**
3740 * Returns the regexp string that defines the format of the human-readable
3741 * size representation, <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
3742 *
3743 * This regexp will capture 5 groups of text:
3744 * - cap(1): integer number in case when no decimal point is present
3745 * (if empty, it means that decimal point is present)
3746 * - cap(2): size suffix in case when no decimal point is present (may be empty)
3747 * - cap(3): integer number in case when decimal point is present (may be empty)
3748 * - cap(4): fraction number (hundredth) in case when decimal point is present
3749 * - cap(5): size suffix in case when decimal point is present (note that
3750 * B cannot appear there)
3751 */
3752/* static */
3753QString VBoxGlobal::sizeRegexp()
3754{
3755 QString regexp =
3756 QString ("^(?:(?:(\\d+)(?:\\s?([KMGTP]?B))?)|(?:(\\d*)%1(\\d{1,2})(?:\\s?([KMGTP]B))))$")
3757 .arg (decimalSep());
3758 return regexp;
3759}
3760
3761/**
3762 * Parses the given size string that should be in form of
3763 * <tt>####[.##] B|KB|MB|GB|TB|PB</tt> and returns the size value
3764 * in bytes. Zero is returned on error.
3765 */
3766/* static */
3767quint64 VBoxGlobal::parseSize (const QString &aText)
3768{
3769 QRegExp regexp (sizeRegexp());
3770 int pos = regexp.indexIn (aText);
3771 if (pos != -1)
3772 {
3773 QString intgS = regexp.cap (1);
3774 QString hundS;
3775 QString suff = regexp.cap (2);
3776 if (intgS.isEmpty())
3777 {
3778 intgS = regexp.cap (3);
3779 hundS = regexp.cap (4);
3780 suff = regexp.cap (5);
3781 }
3782
3783 quint64 denom = 0;
3784 if (suff.isEmpty() || suff == "B")
3785 denom = 1;
3786 else if (suff == "KB")
3787 denom = _1K;
3788 else if (suff == "MB")
3789 denom = _1M;
3790 else if (suff == "GB")
3791 denom = _1G;
3792 else if (suff == "TB")
3793 denom = _1T;
3794 else if (suff == "PB")
3795 denom = _1P;
3796
3797 quint64 intg = intgS.toULongLong();
3798 if (denom == 1)
3799 return intg;
3800
3801 quint64 hund = hundS.leftJustified (2, '0').toULongLong();
3802 hund = hund * denom / 100;
3803 intg = intg * denom + hund;
3804 return intg;
3805 }
3806 else
3807 return 0;
3808}
3809
3810/**
3811 * Formats the given \a size value in bytes to a human readable string
3812 * in form of <tt>####[.##] B|KB|MB|GB|TB|PB</tt>.
3813 *
3814 * The \a mode parameter is used for resulting numbers that get a fractional
3815 * part after converting the \a size to KB, MB etc:
3816 * <ul>
3817 * <li>When \a mode is 0, the result is rounded to the closest number
3818 * containing two decimal digits.
3819 * </li>
3820 * <li>When \a mode is -1, the result is rounded to the largest two decimal
3821 * digit number that is not greater than the result. This guarantees that
3822 * converting the resulting string back to the integer value in bytes
3823 * will not produce a value greater that the initial \a size parameter.
3824 * </li>
3825 * <li>When \a mode is 1, the result is rounded to the smallest two decimal
3826 * digit number that is not less than the result. This guarantees that
3827 * converting the resulting string back to the integer value in bytes
3828 * will not produce a value less that the initial \a size parameter.
3829 * </li>
3830 * </ul>
3831 *
3832 * @param aSize size value in bytes
3833 * @param aMode convertion mode (-1, 0 or 1)
3834 * @return human-readable size string
3835 */
3836/* static */
3837QString VBoxGlobal::formatSize (quint64 aSize, int aMode /* = 0 */)
3838{
3839 static const char *Suffixes [] = { "B", "KB", "MB", "GB", "TB", "PB", NULL };
3840
3841 quint64 denom = 0;
3842 int suffix = 0;
3843
3844 if (aSize < _1K)
3845 {
3846 denom = 1;
3847 suffix = 0;
3848 }
3849 else if (aSize < _1M)
3850 {
3851 denom = _1K;
3852 suffix = 1;
3853 }
3854 else if (aSize < _1G)
3855 {
3856 denom = _1M;
3857 suffix = 2;
3858 }
3859 else if (aSize < _1T)
3860 {
3861 denom = _1G;
3862 suffix = 3;
3863 }
3864 else if (aSize < _1P)
3865 {
3866 denom = _1T;
3867 suffix = 4;
3868 }
3869 else
3870 {
3871 denom = _1P;
3872 suffix = 5;
3873 }
3874
3875 quint64 intg = aSize / denom;
3876 quint64 hund = aSize % denom;
3877
3878 QString number;
3879 if (denom > 1)
3880 {
3881 if (hund)
3882 {
3883 hund *= 100;
3884 /* not greater */
3885 if (aMode < 0) hund = hund / denom;
3886 /* not less */
3887 else if (aMode > 0) hund = (hund + denom - 1) / denom;
3888 /* nearest */
3889 else hund = (hund + denom / 2) / denom;
3890 }
3891 /* check for the fractional part overflow due to rounding */
3892 if (hund == 100)
3893 {
3894 hund = 0;
3895 ++ intg;
3896 /* check if we've got 1024 XB after rounding and scale down if so */
3897 if (intg == 1024 && Suffixes [suffix + 1] != NULL)
3898 {
3899 intg /= 1024;
3900 ++ suffix;
3901 }
3902 }
3903 number = QString ("%1%2%3").arg (intg).arg (decimalSep())
3904 .arg (QString::number (hund).rightJustified (2, '0'));
3905 }
3906 else
3907 {
3908 number = QString::number (intg);
3909 }
3910
3911 return QString ("%1 %2").arg (number).arg (Suffixes [suffix]);
3912}
3913
3914/**
3915 * Puts soft hyphens after every path component in the given file name.
3916 *
3917 * @param aFileName File name (must be a full path name).
3918 */
3919/* static */
3920QString VBoxGlobal::locationForHTML (const QString &aFileName)
3921{
3922/// @todo (dmik) remove?
3923// QString result = QDir::toNativeSeparators (fn);
3924//#ifdef Q_OS_LINUX
3925// result.replace ('/', "/<font color=red>&shy;</font>");
3926//#else
3927// result.replace ('\\', "\\<font color=red>&shy;</font>");
3928//#endif
3929// return result;
3930 QFileInfo fi (aFileName);
3931 return fi.fileName();
3932}
3933
3934/**
3935 * Reformats the input string @a aStr so that:
3936 * - strings in single quotes will be put inside <nobr> and marked
3937 * with blue color;
3938 * - UUIDs be put inside <nobr> and marked
3939 * with green color;
3940 * - replaces new line chars with </p><p> constructs to form paragraphs
3941 * (note that <p> and </p> are not appended to the beginnign and to the
3942 * end of the string respectively, to allow the result be appended
3943 * or prepended to the existing paragraph).
3944 *
3945 * If @a aToolTip is true, colouring is not applied, only the <nobr> tag
3946 * is added. Also, new line chars are replaced with <br> instead of <p>.
3947 */
3948/* static */
3949QString VBoxGlobal::highlight (const QString &aStr, bool aToolTip /* = false */)
3950{
3951 QString strFont;
3952 QString uuidFont;
3953 QString endFont;
3954 if (!aToolTip)
3955 {
3956 strFont = "<font color=#0000CC>";
3957 uuidFont = "<font color=#008000>";
3958 endFont = "</font>";
3959 }
3960
3961 QString text = aStr;
3962
3963 /* replace special entities, '&' -- first! */
3964 text.replace ('&', "&amp;");
3965 text.replace ('<', "&lt;");
3966 text.replace ('>', "&gt;");
3967 text.replace ('\"', "&quot;");
3968
3969 /* mark strings in single quotes with color */
3970 QRegExp rx = QRegExp ("((?:^|\\s)[(]?)'([^']*)'(?=[:.-!);]?(?:\\s|$))");
3971 rx.setMinimal (true);
3972 text.replace (rx,
3973 QString ("\\1%1<nobr>'\\2'</nobr>%2")
3974 .arg (strFont). arg (endFont));
3975
3976 /* mark UUIDs with color */
3977 text.replace (QRegExp (
3978 "((?:^|\\s)[(]?)"
3979 "(\\{[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}\\})"
3980 "(?=[:.-!);]?(?:\\s|$))"),
3981 QString ("\\1%1<nobr>\\2</nobr>%2")
3982 .arg (uuidFont). arg (endFont));
3983
3984 /* split to paragraphs at \n chars */
3985 if (!aToolTip)
3986 text.replace ('\n', "</p><p>");
3987 else
3988 text.replace ('\n', "<br>");
3989
3990 return text;
3991}
3992
3993/**
3994 * This does exactly the same as QLocale::system().name() but corrects its
3995 * wrong behavior on Linux systems (LC_NUMERIC for some strange reason takes
3996 * precedence over any other locale setting in the QLocale::system()
3997 * implementation). This implementation first looks at LC_ALL (as defined by
3998 * SUS), then looks at LC_MESSAGES which is designed to define a language for
3999 * program messages in case if it differs from the language for other locale
4000 * categories. Then it looks for LANG and finally falls back to
4001 * QLocale::system().name().
4002 *
4003 * The order of precedence is well defined here:
4004 * http://opengroup.org/onlinepubs/007908799/xbd/envvar.html
4005 *
4006 * @note This method will return "C" when the requested locale is invalid or
4007 * when the "C" locale is set explicitly.
4008 */
4009/* static */
4010QString VBoxGlobal::systemLanguageId()
4011{
4012#if defined (Q_WS_MAC)
4013 /* QLocale return the right id only if the user select the format of the
4014 * language also. So we use our own implementation */
4015 return ::darwinSystemLanguage();
4016#elif defined (Q_OS_UNIX)
4017 const char *s = RTEnvGet ("LC_ALL");
4018 if (s == 0)
4019 s = RTEnvGet ("LC_MESSAGES");
4020 if (s == 0)
4021 s = RTEnvGet ("LANG");
4022 if (s != 0)
4023 return QLocale (s).name();
4024#endif
4025 return QLocale::system().name();
4026}
4027
4028/**
4029 * Reimplementation of QFileDialog::getExistingDirectory() that removes some
4030 * oddities and limitations.
4031 *
4032 * On Win32, this function makes sure a native dialog is launched in
4033 * another thread to avoid dialog visualization errors occuring due to
4034 * multi-threaded COM apartment initialization on the main UI thread while
4035 * the appropriate native dialog function expects a single-threaded one.
4036 *
4037 * On all other platforms, this function is equivalent to
4038 * QFileDialog::getExistingDirectory().
4039 */
4040QString VBoxGlobal::getExistingDirectory (const QString &aDir,
4041 QWidget *aParent,
4042 const QString &aCaption,
4043 bool aDirOnly,
4044 bool aResolveSymlinks)
4045{
4046#if defined Q_WS_WIN
4047
4048 /**
4049 * QEvent class reimplementation to carry Win32 API native dialog's
4050 * result folder information
4051 */
4052 class GetExistDirectoryEvent : public OpenNativeDialogEvent
4053 {
4054 public:
4055
4056 enum { TypeId = QEvent::User + 300 };
4057
4058 GetExistDirectoryEvent (const QString &aResult)
4059 : OpenNativeDialogEvent (aResult, (QEvent::Type) TypeId) {}
4060 };
4061
4062 /**
4063 * QThread class reimplementation to open Win32 API native folder's dialog
4064 */
4065 class Thread : public QThread
4066 {
4067 public:
4068
4069 Thread (QWidget *aParent, QObject *aTarget,
4070 const QString &aDir, const QString &aCaption)
4071 : mParent (aParent), mTarget (aTarget), mDir (aDir), mCaption (aCaption) {}
4072
4073 virtual void run()
4074 {
4075 QString result;
4076
4077 QWidget *topParent = mParent ? mParent->window() : vboxGlobal().mainWindow();
4078 QString title = mCaption.isNull() ? tr ("Select a directory") : mCaption;
4079
4080 TCHAR path[MAX_PATH];
4081 path [0] = 0;
4082 TCHAR initPath [MAX_PATH];
4083 initPath [0] = 0;
4084
4085 BROWSEINFO bi;
4086 bi.hwndOwner = topParent ? topParent->winId() : 0;
4087 bi.pidlRoot = NULL;
4088 bi.lpszTitle = (TCHAR*)(title.isNull() ? 0 : title.utf16());
4089 bi.pszDisplayName = initPath;
4090 bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
4091 bi.lpfn = winGetExistDirCallbackProc;
4092 bi.lParam = Q_ULONG (&mDir);
4093
4094 /* Qt is uncapable to properly handle modal state if the modal
4095 * window is not a QWidget. For example, if we have the W1->W2->N
4096 * ownership where Wx are QWidgets (W2 is modal), and N is a
4097 * native modal window, cliking on the title bar of W1 will still
4098 * activate W2 and redirect keyboard/mouse to it. The dirty hack
4099 * to prevent it is to disable the entire widget... */
4100 if (mParent)
4101 mParent->setEnabled (false);
4102
4103 LPITEMIDLIST itemIdList = SHBrowseForFolder (&bi);
4104 if (itemIdList)
4105 {
4106 SHGetPathFromIDList (itemIdList, path);
4107 IMalloc *pMalloc;
4108 if (SHGetMalloc (&pMalloc) != NOERROR)
4109 result = QString::null;
4110 else
4111 {
4112 pMalloc->Free (itemIdList);
4113 pMalloc->Release();
4114 result = QString::fromUtf16 ((ushort*)path);
4115 }
4116 }
4117 else
4118 result = QString::null;
4119 QApplication::postEvent (mTarget, new GetExistDirectoryEvent (result));
4120
4121 /* Enable the parent widget again. */
4122 if (mParent)
4123 mParent->setEnabled (true);
4124 }
4125
4126 private:
4127
4128 QWidget *mParent;
4129 QObject *mTarget;
4130 QString mDir;
4131 QString mCaption;
4132 };
4133
4134 /* Local event loop to run while waiting for the result from another
4135 * thread */
4136 QEventLoop loop;
4137
4138 QString dir = QDir::toNativeSeparators (aDir);
4139 LoopObject loopObject ((QEvent::Type) GetExistDirectoryEvent::TypeId, loop);
4140
4141 Thread openDirThread (aParent, &loopObject, dir, aCaption);
4142 openDirThread.start();
4143 loop.exec();
4144 openDirThread.wait();
4145
4146 return loopObject.result();
4147
4148#elif defined (Q_WS_X11) && (QT_VERSION < 0x040400)
4149
4150 /* Here is workaround for Qt4.3 bug with QFileDialog which crushes when
4151 * gets initial path as hidden directory if no hidden files are shown.
4152 * See http://trolltech.com/developer/task-tracker/index_html?method=entry&id=193483
4153 * for details */
4154 QFileDialog dlg (aParent);
4155 dlg.setWindowTitle (aCaption);
4156 dlg.setDirectory (aDir);
4157 dlg.setResolveSymlinks (aResolveSymlinks);
4158 dlg.setFileMode (aDirOnly ? QFileDialog::DirectoryOnly : QFileDialog::Directory);
4159 QAction *hidden = dlg.findChild <QAction*> ("qt_show_hidden_action");
4160 if (hidden)
4161 {
4162 hidden->trigger();
4163 hidden->setVisible (false);
4164 }
4165 return dlg.exec() ? dlg.selectedFiles() [0] : QString::null;
4166
4167#else
4168
4169 QFileDialog::Options o;
4170 if (aDirOnly)
4171 o = QFileDialog::ShowDirsOnly;
4172 if (!aResolveSymlinks)
4173 o |= QFileDialog::DontResolveSymlinks;
4174 return QFileDialog::getExistingDirectory (aParent, aCaption, aDir, o);
4175
4176#endif
4177}
4178
4179/**
4180 * Reimplementation of QFileDialog::getOpenFileName() that removes some
4181 * oddities and limitations.
4182 *
4183 * On Win32, this function makes sure a file filter is applied automatically
4184 * right after it is selected from the drop-down list, to conform to common
4185 * experience in other applications. Note that currently, @a selectedFilter
4186 * is always set to null on return.
4187 *
4188 * On all other platforms, this function is equivalent to
4189 * QFileDialog::getOpenFileName().
4190 */
4191/* static */
4192QString VBoxGlobal::getOpenFileName (const QString &aStartWith,
4193 const QString &aFilters,
4194 QWidget *aParent,
4195 const QString &aCaption,
4196 QString *aSelectedFilter /* = NULL */,
4197 bool aResolveSymlinks /* = true */)
4198{
4199 return getOpenFileNames (aStartWith,
4200 aFilters,
4201 aParent,
4202 aCaption,
4203 aSelectedFilter,
4204 aResolveSymlinks,
4205 true /* aSingleFile */).value (0, "");
4206}
4207
4208/**
4209 * Reimplementation of QFileDialog::getOpenFileNames() that removes some
4210 * oddities and limitations.
4211 *
4212 * On Win32, this function makes sure a file filter is applied automatically
4213 * right after it is selected from the drop-down list, to conform to common
4214 * experience in other applications. Note that currently, @a selectedFilter
4215 * is always set to null on return.
4216 * @todo: implement the multiple file selection on win
4217 * @todo: is this extra handling on win still necessary with Qt4?
4218 *
4219 * On all other platforms, this function is equivalent to
4220 * QFileDialog::getOpenFileNames().
4221 */
4222/* static */
4223QStringList VBoxGlobal::getOpenFileNames (const QString &aStartWith,
4224 const QString &aFilters,
4225 QWidget *aParent,
4226 const QString &aCaption,
4227 QString *aSelectedFilter /* = NULL */,
4228 bool aResolveSymlinks /* = true */,
4229 bool aSingleFile /* = false */)
4230{
4231#if defined Q_WS_WIN
4232
4233 /**
4234 * QEvent class reimplementation to carry Win32 API native dialog's
4235 * result folder information
4236 */
4237 class GetOpenFileNameEvent : public OpenNativeDialogEvent
4238 {
4239 public:
4240
4241 enum { TypeId = QEvent::User + 301 };
4242
4243 GetOpenFileNameEvent (const QString &aResult)
4244 : OpenNativeDialogEvent (aResult, (QEvent::Type) TypeId) {}
4245 };
4246
4247 /**
4248 * QThread class reimplementation to open Win32 API native file dialog
4249 */
4250 class Thread : public QThread
4251 {
4252 public:
4253
4254 Thread (QWidget *aParent, QObject *aTarget,
4255 const QString &aStartWith, const QString &aFilters,
4256 const QString &aCaption) :
4257 mParent (aParent), mTarget (aTarget),
4258 mStartWith (aStartWith), mFilters (aFilters),
4259 mCaption (aCaption) {}
4260
4261 virtual void run()
4262 {
4263 QString result;
4264
4265 QString workDir;
4266 QString initSel;
4267 QFileInfo fi (mStartWith);
4268
4269 if (fi.isDir())
4270 workDir = mStartWith;
4271 else
4272 {
4273 workDir = fi.absolutePath();
4274 initSel = fi.fileName();
4275 }
4276
4277 workDir = QDir::toNativeSeparators (workDir);
4278 if (!workDir.endsWith ("\\"))
4279 workDir += "\\";
4280
4281 QString title = mCaption.isNull() ? tr ("Select a file") : mCaption;
4282
4283 QWidget *topParent = mParent ? mParent->window() : vboxGlobal().mainWindow();
4284 QString winFilters = winFilter (mFilters);
4285 AssertCompile (sizeof (TCHAR) == sizeof (QChar));
4286 TCHAR buf [1024];
4287 if (initSel.length() > 0 && initSel.length() < sizeof (buf))
4288 memcpy (buf, initSel.isNull() ? 0 : initSel.utf16(),
4289 (initSel.length() + 1) * sizeof (TCHAR));
4290 else
4291 buf [0] = 0;
4292
4293 OPENFILENAME ofn;
4294 memset (&ofn, 0, sizeof (OPENFILENAME));
4295
4296 ofn.lStructSize = sizeof (OPENFILENAME);
4297 ofn.hwndOwner = topParent ? topParent->winId() : 0;
4298 ofn.lpstrFilter = (TCHAR *) winFilters.isNull() ? 0 : winFilters.utf16();
4299 ofn.lpstrFile = buf;
4300 ofn.nMaxFile = sizeof (buf) - 1;
4301 ofn.lpstrInitialDir = (TCHAR *) workDir.isNull() ? 0 : workDir.utf16();
4302 ofn.lpstrTitle = (TCHAR *) title.isNull() ? 0 : title.utf16();
4303 ofn.Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY |
4304 OFN_EXPLORER | OFN_ENABLEHOOK |
4305 OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST);
4306 ofn.lpfnHook = OFNHookProc;
4307
4308 if (GetOpenFileName (&ofn))
4309 {
4310 result = QString::fromUtf16 ((ushort *) ofn.lpstrFile);
4311 }
4312
4313 // qt_win_eatMouseMove();
4314 MSG msg = {0, 0, 0, 0, 0, 0, 0};
4315 while (PeekMessage (&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
4316 if (msg.message == WM_MOUSEMOVE)
4317 PostMessage (msg.hwnd, msg.message, 0, msg.lParam);
4318
4319 result = result.isEmpty() ? result : QFileInfo (result).absoluteFilePath();
4320
4321 QApplication::postEvent (mTarget, new GetOpenFileNameEvent (result));
4322 }
4323
4324 private:
4325
4326 QWidget *mParent;
4327 QObject *mTarget;
4328 QString mStartWith;
4329 QString mFilters;
4330 QString mCaption;
4331 };
4332
4333 if (aSelectedFilter)
4334 *aSelectedFilter = QString::null;
4335
4336 /* Local event loop to run while waiting for the result from another
4337 * thread */
4338 QEventLoop loop;
4339
4340 QString startWith = QDir::toNativeSeparators (aStartWith);
4341 LoopObject loopObject ((QEvent::Type) GetOpenFileNameEvent::TypeId, loop);
4342
4343//#warning check me!
4344 if (aParent)
4345 aParent->setWindowModality (Qt::WindowModal);
4346
4347 Thread openDirThread (aParent, &loopObject, startWith, aFilters, aCaption);
4348 openDirThread.start();
4349 loop.exec();
4350 openDirThread.wait();
4351
4352//#warning check me!
4353 if (aParent)
4354 aParent->setWindowModality (Qt::NonModal);
4355
4356 return QStringList() << loopObject.result();
4357
4358#elif defined (Q_WS_X11) && (QT_VERSION < 0x040400)
4359
4360 /* Here is workaround for Qt4.3 bug with QFileDialog which crushes when
4361 * gets initial path as hidden directory if no hidden files are shown.
4362 * See http://trolltech.com/developer/task-tracker/index_html?method=entry&id=193483
4363 * for details */
4364 QFileDialog dlg (aParent);
4365 dlg.setWindowTitle (aCaption);
4366 dlg.setDirectory (aStartWith);
4367 dlg.setFilter (aFilters);
4368 if (aSingleFile)
4369 dlg.setFileMode (QFileDialog::ExistingFile);
4370 else
4371 dlg.setFileMode (QFileDialog::ExistingFiles);
4372 if (aSelectedFilter)
4373 dlg.selectFilter (*aSelectedFilter);
4374 dlg.setResolveSymlinks (aResolveSymlinks);
4375 QAction *hidden = dlg.findChild <QAction*> ("qt_show_hidden_action");
4376 if (hidden)
4377 {
4378 hidden->trigger();
4379 hidden->setVisible (false);
4380 }
4381 return dlg.exec() == QDialog::Accepted ? dlg.selectedFiles() : QStringList() << QString::null;
4382
4383#else
4384
4385 QFileDialog::Options o;
4386 if (!aResolveSymlinks)
4387 o |= QFileDialog::DontResolveSymlinks;
4388 if (aSingleFile)
4389 return QStringList() << QFileDialog::getOpenFileName (aParent, aCaption, aStartWith,
4390 aFilters, aSelectedFilter, o);
4391 else
4392 return QFileDialog::getOpenFileNames (aParent, aCaption, aStartWith,
4393 aFilters, aSelectedFilter, o);
4394#endif
4395}
4396
4397/**
4398 * Search for the first directory that exists starting from the passed one
4399 * and going up through its parents. In case if none of the directories
4400 * exist (except the root one), the function returns QString::null.
4401 */
4402/* static */
4403QString VBoxGlobal::getFirstExistingDir (const QString &aStartDir)
4404{
4405 QString result = QString::null;
4406 QDir dir (aStartDir);
4407 while (!dir.exists() && !dir.isRoot())
4408 {
4409 QFileInfo dirInfo (dir.absolutePath());
4410 dir = dirInfo.absolutePath();
4411 }
4412 if (dir.exists() && !dir.isRoot())
4413 result = dir.absolutePath();
4414 return result;
4415}
4416
4417#if defined (Q_WS_X11)
4418
4419static char *XXGetProperty (Display *aDpy, Window aWnd,
4420 Atom aPropType, const char *aPropName)
4421{
4422 Atom propNameAtom = XInternAtom (aDpy, aPropName,
4423 True /* only_if_exists */);
4424 if (propNameAtom == None)
4425 return NULL;
4426
4427 Atom actTypeAtom = None;
4428 int actFmt = 0;
4429 unsigned long nItems = 0;
4430 unsigned long nBytesAfter = 0;
4431 unsigned char *propVal = NULL;
4432 int rc = XGetWindowProperty (aDpy, aWnd, propNameAtom,
4433 0, LONG_MAX, False /* delete */,
4434 aPropType, &actTypeAtom, &actFmt,
4435 &nItems, &nBytesAfter, &propVal);
4436 if (rc != Success)
4437 return NULL;
4438
4439 return reinterpret_cast <char *> (propVal);
4440}
4441
4442static Bool XXSendClientMessage (Display *aDpy, Window aWnd, const char *aMsg,
4443 unsigned long aData0 = 0, unsigned long aData1 = 0,
4444 unsigned long aData2 = 0, unsigned long aData3 = 0,
4445 unsigned long aData4 = 0)
4446{
4447 Atom msgAtom = XInternAtom (aDpy, aMsg, True /* only_if_exists */);
4448 if (msgAtom == None)
4449 return False;
4450
4451 XEvent ev;
4452
4453 ev.xclient.type = ClientMessage;
4454 ev.xclient.serial = 0;
4455 ev.xclient.send_event = True;
4456 ev.xclient.display = aDpy;
4457 ev.xclient.window = aWnd;
4458 ev.xclient.message_type = msgAtom;
4459
4460 /* always send as 32 bit for now */
4461 ev.xclient.format = 32;
4462 ev.xclient.data.l [0] = aData0;
4463 ev.xclient.data.l [1] = aData1;
4464 ev.xclient.data.l [2] = aData2;
4465 ev.xclient.data.l [3] = aData3;
4466 ev.xclient.data.l [4] = aData4;
4467
4468 return XSendEvent (aDpy, DefaultRootWindow (aDpy), False,
4469 SubstructureRedirectMask, &ev) != 0;
4470}
4471
4472#endif
4473
4474/**
4475 * Activates the specified window. If necessary, the window will be
4476 * de-iconified activation.
4477 *
4478 * @note On X11, it is implied that @a aWid represents a window of the same
4479 * display the application was started on.
4480 *
4481 * @param aWId Window ID to activate.
4482 * @param aSwitchDesktop @c true to switch to the window's desktop before
4483 * activation.
4484 *
4485 * @return @c true on success and @c false otherwise.
4486 */
4487/* static */
4488bool VBoxGlobal::activateWindow (WId aWId, bool aSwitchDesktop /* = true */)
4489{
4490 bool result = true;
4491
4492#if defined (Q_WS_WIN32)
4493
4494 if (IsIconic (aWId))
4495 result &= !!ShowWindow (aWId, SW_RESTORE);
4496 else if (!IsWindowVisible (aWId))
4497 result &= !!ShowWindow (aWId, SW_SHOW);
4498
4499 result &= !!SetForegroundWindow (aWId);
4500
4501#elif defined (Q_WS_X11)
4502
4503 Display *dpy = QX11Info::display();
4504
4505 if (aSwitchDesktop)
4506 {
4507 /* try to find the desktop ID using the NetWM property */
4508 CARD32 *desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
4509 "_NET_WM_DESKTOP");
4510 if (desktop == NULL)
4511 /* if the NetWM propery is not supported try to find the desktop
4512 * ID using the GNOME WM property */
4513 desktop = (CARD32 *) XXGetProperty (dpy, aWId, XA_CARDINAL,
4514 "_WIN_WORKSPACE");
4515
4516 if (desktop != NULL)
4517 {
4518 Bool ok = XXSendClientMessage (dpy, DefaultRootWindow (dpy),
4519 "_NET_CURRENT_DESKTOP",
4520 *desktop);
4521 if (!ok)
4522 {
4523 LogWarningFunc (("Couldn't switch to desktop=%08X\n",
4524 desktop));
4525 result = false;
4526 }
4527 XFree (desktop);
4528 }
4529 else
4530 {
4531 LogWarningFunc (("Couldn't find a desktop ID for aWId=%08X\n",
4532 aWId));
4533 result = false;
4534 }
4535 }
4536
4537 Bool ok = XXSendClientMessage (dpy, aWId, "_NET_ACTIVE_WINDOW");
4538 result &= !!ok;
4539
4540 XRaiseWindow (dpy, aWId);
4541
4542#else
4543
4544 NOREF (aSwitchDesktop);
4545 AssertFailed();
4546 result = false;
4547
4548#endif
4549
4550 if (!result)
4551 LogWarningFunc (("Couldn't activate aWId=%08X\n", aWId));
4552
4553 return result;
4554}
4555
4556/**
4557 * Removes the acceletartor mark (the ampersand symbol) from the given string
4558 * and returns the result. The string is supposed to be a menu item's text
4559 * that may (or may not) contain the accelerator mark.
4560 *
4561 * In order to support accelerators used in non-alphabet languages
4562 * (e.g. Japanese) that has a form of "(&<L>)" (where <L> is a latin letter),
4563 * this method first searches for this pattern and, if found, removes it as a
4564 * whole. If such a pattern is not found, then the '&' character is simply
4565 * removed from the string.
4566 *
4567 * @note This function removes only the first occurense of the accelerator
4568 * mark.
4569 *
4570 * @param aText Menu item's text to remove the acceletaror mark from.
4571 *
4572 * @return The resulting string.
4573 */
4574/* static */
4575QString VBoxGlobal::removeAccelMark (const QString &aText)
4576{
4577 QString result = aText;
4578
4579 QRegExp accel ("\\(&[a-zA-Z]\\)");
4580 int pos = accel.indexIn (result);
4581 if (pos >= 0)
4582 result.remove (pos, accel.cap().length());
4583 else
4584 {
4585 pos = result.indexOf ('&');
4586 if (pos >= 0)
4587 result.remove (pos, 1);
4588 }
4589
4590 return result;
4591}
4592
4593/* static */
4594QString VBoxGlobal::insertKeyToActionText (const QString &aText, const QString &aKey)
4595{
4596#ifdef Q_WS_MAC
4597 QString key ("%1 (Host+%2)");
4598#else
4599 QString key ("%1 \tHost+%2");
4600#endif
4601 return key.arg (aText).arg (QKeySequence (aKey).toString (QKeySequence::NativeText));
4602}
4603
4604/* static */
4605QString VBoxGlobal::extractKeyFromActionText (const QString &aText)
4606{
4607 QString key;
4608#ifdef Q_WS_MAC
4609 QRegExp re (".* \\(Host\\+(.+)\\)");
4610#else
4611 QRegExp re (".* \\t\\Host\\+(.+)");
4612#endif
4613 if (re.exactMatch (aText))
4614 key = re.cap (1);
4615 return key;
4616}
4617
4618/**
4619 * Joins two pixmaps horizontally with 2px space between them and returns the
4620 * result.
4621 *
4622 * @param aPM1 Left pixmap.
4623 * @param aPM2 Right pixmap.
4624 */
4625/* static */
4626QPixmap VBoxGlobal::joinPixmaps (const QPixmap &aPM1, const QPixmap &aPM2)
4627{
4628 if (aPM1.isNull())
4629 return aPM2;
4630 if (aPM2.isNull())
4631 return aPM1;
4632
4633 QPixmap result (aPM1.width() + aPM2.width() + 2,
4634 qMax (aPM1.height(), aPM2.height()));
4635 result.fill (Qt::transparent);
4636
4637 QPainter painter (&result);
4638 painter.drawPixmap (0, 0, aPM1);
4639 painter.drawPixmap (aPM1.width() + 2, result.height() - aPM2.height(), aPM2);
4640 painter.end();
4641
4642 return result;
4643}
4644
4645/**
4646 * Searches for a widget that with @a aName (if it is not NULL) which inherits
4647 * @a aClassName (if it is not NULL) and among children of @a aParent. If @a
4648 * aParent is NULL, all top-level widgets are searched. If @a aRecursive is
4649 * true, child widgets are recursively searched as well.
4650 */
4651/* static */
4652QWidget *VBoxGlobal::findWidget (QWidget *aParent, const char *aName,
4653 const char *aClassName /* = NULL */,
4654 bool aRecursive /* = false */)
4655{
4656 if (aParent == NULL)
4657 {
4658 QWidgetList list = QApplication::topLevelWidgets();
4659 QWidget* w = NULL;
4660 foreach(w, list)
4661 {
4662 if ((!aName || strcmp (w->objectName().toAscii().constData(), aName) == 0) &&
4663 (!aClassName || strcmp (w->metaObject()->className(), aClassName) == 0))
4664 break;
4665 if (aRecursive)
4666 {
4667 w = findWidget (w, aName, aClassName, aRecursive);
4668 if (w)
4669 break;
4670 }
4671 }
4672 return w;
4673 }
4674
4675 /* Find the first children of aParent with the appropriate properties.
4676 * Please note that this call is recursivly. */
4677 QList<QWidget *> list = qFindChildren<QWidget *> (aParent, aName);
4678 QWidget *child = NULL;
4679 foreach(child, list)
4680 {
4681 if (!aClassName || strcmp (child->metaObject()->className(), aClassName) == 0)
4682 break;
4683 }
4684 return child;
4685}
4686
4687/**
4688 * Figures out which hard disk formats are currently supported by VirtualBox.
4689 * Returned is a list of pairs with the form
4690 * <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>.
4691 */
4692/* static */
4693QList <QPair <QString, QString> > VBoxGlobal::HDDBackends()
4694{
4695 CSystemProperties systemProperties = vboxGlobal().virtualBox().GetSystemProperties();
4696 QVector<CHardDiskFormat> hardDiskFormats = systemProperties.GetHardDiskFormats();
4697 QList< QPair<QString, QString> > backendPropList;
4698 for (int i = 0; i < hardDiskFormats.size(); ++ i)
4699 {
4700 /* File extensions */
4701 QVector <QString> fileExtensions = hardDiskFormats [i].GetFileExtensions();
4702 QStringList f;
4703 for (int a = 0; a < fileExtensions.size(); ++ a)
4704 f << QString ("*.%1").arg (fileExtensions [a]);
4705 /* Create a pair out of the backend description and all suffix's. */
4706 if (!f.isEmpty())
4707 backendPropList << QPair<QString, QString> (hardDiskFormats [i].GetName(), f.join(" "));
4708 }
4709 return backendPropList;
4710}
4711
4712// Public slots
4713////////////////////////////////////////////////////////////////////////////////
4714
4715/**
4716 * Opens the specified URL using OS/Desktop capabilities.
4717 *
4718 * @param aURL URL to open
4719 *
4720 * @return true on success and false otherwise
4721 */
4722bool VBoxGlobal::openURL (const QString &aURL)
4723{
4724#if defined (Q_WS_WIN)
4725 /* We cannot use ShellExecute() on the main UI thread because we've
4726 * initialized COM with CoInitializeEx(COINIT_MULTITHREADED). See
4727 * http://support.microsoft.com/default.aspx?scid=kb;en-us;287087
4728 * for more details. */
4729 class Thread : public QThread
4730 {
4731 public:
4732
4733 Thread (const QString &aURL, QObject *aObject)
4734 : mObject (aObject), mURL (aURL) {}
4735
4736 void run()
4737 {
4738 int rc = (int) ShellExecute (NULL, NULL, mURL.isNull() ? 0 : mURL.utf16(),
4739 NULL, NULL, SW_SHOW);
4740 bool ok = rc > 32;
4741 QApplication::postEvent
4742 (mObject,
4743 new VBoxShellExecuteEvent (this, mURL, ok));
4744 }
4745
4746 QString mURL;
4747 QObject *mObject;
4748 };
4749
4750 Thread *thread = new Thread (aURL, this);
4751 thread->start();
4752 /* thread will be deleted in the VBoxShellExecuteEvent handler */
4753
4754 return true;
4755
4756#elif defined (Q_WS_X11)
4757
4758 static const char * const commands[] =
4759 { "kfmclient:exec", "gnome-open", "x-www-browser", "firefox", "konqueror" };
4760
4761 for (size_t i = 0; i < RT_ELEMENTS (commands); ++ i)
4762 {
4763 QStringList args = QString(commands [i]).split (':');
4764 args += aURL;
4765 QString command = args.takeFirst();
4766 if (QProcess::startDetached (command, args))
4767 return true;
4768 }
4769
4770#elif defined (Q_WS_MAC)
4771
4772 /* The code below is taken from Psi 0.10 sources
4773 * (http://www.psi-im.org) */
4774
4775 /* Use Internet Config to hand the URL to the appropriate application, as
4776 * set by the user in the Internet Preferences pane.
4777 * NOTE: ICStart could be called once at Psi startup, saving the
4778 * ICInstance in a global variable, as a minor optimization.
4779 * ICStop should then be called at Psi shutdown if ICStart
4780 * succeeded. */
4781 ICInstance icInstance;
4782 OSType psiSignature = 'psi ';
4783 OSStatus error = ::ICStart (&icInstance, psiSignature);
4784 if (error == noErr)
4785 {
4786 ConstStr255Param hint (0x0);
4787 QByteArray cs = aURL.toLocal8Bit();
4788 const char* data = cs.data();
4789 long length = cs.length();
4790 long start (0);
4791 long end (length);
4792 /* Don't bother testing return value (error); launched application
4793 * will report problems. */
4794 ::ICLaunchURL (icInstance, hint, data, length, &start, &end);
4795 ICStop (icInstance);
4796 return true;
4797 }
4798
4799#else
4800 vboxProblem().message
4801 (NULL, VBoxProblemReporter::Error,
4802 tr ("Opening URLs is not implemented yet."));
4803 return false;
4804#endif
4805
4806 /* if we go here it means we couldn't open the URL */
4807 vboxProblem().cannotOpenURL (aURL);
4808
4809 return false;
4810}
4811
4812/**
4813 * Shows the VirtualBox registration dialog.
4814 *
4815 * @note that this method is not part of VBoxProblemReporter (like e.g.
4816 * VBoxProblemReporter::showHelpAboutDialog()) because it is tied to
4817 * VBoxCallback::OnExtraDataChange() handling performed by VBoxGlobal.
4818 *
4819 * @param aForce
4820 */
4821void VBoxGlobal::showRegistrationDialog (bool aForce)
4822{
4823#ifdef VBOX_WITH_REGISTRATION
4824 if (!aForce && !VBoxRegistrationDlg::hasToBeShown())
4825 return;
4826
4827 if (mRegDlg)
4828 {
4829 /* Show the already opened registration dialog */
4830 mRegDlg->setWindowState (mRegDlg->windowState() & ~Qt::WindowMinimized);
4831 mRegDlg->raise();
4832 mRegDlg->activateWindow();
4833 }
4834 else
4835 {
4836 /* Store the ID of the main window to ensure that only one
4837 * registration dialog is shown at a time. Due to manipulations with
4838 * OnExtraDataCanChange() and OnExtraDataChange() signals, this extra
4839 * data item acts like an inter-process mutex, so the first process
4840 * that attempts to set it will win, the rest will get a failure from
4841 * the SetExtraData() call. */
4842 mVBox.SetExtraData (VBoxDefs::GUI_RegistrationDlgWinID,
4843 QString ("%1").arg ((qulonglong) mMainWindow->winId()));
4844
4845 if (mVBox.isOk())
4846 {
4847 /* We've got the "mutex", create a new registration dialog */
4848 VBoxRegistrationDlg *dlg =
4849 new VBoxRegistrationDlg (&mRegDlg, 0);
4850 dlg->setAttribute (Qt::WA_DeleteOnClose);
4851 Assert (dlg == mRegDlg);
4852 mRegDlg->show();
4853 }
4854 }
4855#endif
4856}
4857
4858/**
4859 * Shows the VirtualBox version check & update dialog.
4860 *
4861 * @note that this method is not part of VBoxProblemReporter (like e.g.
4862 * VBoxProblemReporter::showHelpAboutDialog()) because it is tied to
4863 * VBoxCallback::OnExtraDataChange() handling performed by VBoxGlobal.
4864 *
4865 * @param aForce
4866 */
4867void VBoxGlobal::showUpdateDialog (bool aForce)
4868{
4869 bool isNecessary = VBoxUpdateDlg::isNecessary();
4870
4871 if (!aForce && !isNecessary)
4872 return;
4873
4874 if (mUpdDlg)
4875 {
4876 if (!mUpdDlg->isHidden())
4877 {
4878 mUpdDlg->setWindowState (mUpdDlg->windowState() & ~Qt::WindowMinimized);
4879 mUpdDlg->raise();
4880 mUpdDlg->activateWindow();
4881 }
4882 }
4883 else
4884 {
4885 /* Store the ID of the main window to ensure that only one
4886 * update dialog is shown at a time. Due to manipulations with
4887 * OnExtraDataCanChange() and OnExtraDataChange() signals, this extra
4888 * data item acts like an inter-process mutex, so the first process
4889 * that attempts to set it will win, the rest will get a failure from
4890 * the SetExtraData() call. */
4891 mVBox.SetExtraData (VBoxDefs::GUI_UpdateDlgWinID,
4892 QString ("%1").arg ((qulonglong) mMainWindow->winId()));
4893
4894 if (mVBox.isOk())
4895 {
4896 /* We've got the "mutex", create a new update dialog */
4897 VBoxUpdateDlg *dlg = new VBoxUpdateDlg (&mUpdDlg, aForce, 0);
4898 dlg->setAttribute (Qt::WA_DeleteOnClose);
4899 Assert (dlg == mUpdDlg);
4900
4901 /* Update dialog always in background mode for now.
4902 * if (!aForce && isAutomatic) */
4903 mUpdDlg->search();
4904 /* else mUpdDlg->show(); */
4905 }
4906 }
4907}
4908
4909// Protected members
4910////////////////////////////////////////////////////////////////////////////////
4911
4912bool VBoxGlobal::event (QEvent *e)
4913{
4914 switch (e->type())
4915 {
4916#if defined (Q_WS_WIN)
4917 case VBoxDefs::ShellExecuteEventType:
4918 {
4919 VBoxShellExecuteEvent *ev = (VBoxShellExecuteEvent *) e;
4920 if (!ev->mOk)
4921 vboxProblem().cannotOpenURL (ev->mURL);
4922 /* wait for the thread and free resources */
4923 ev->mThread->wait();
4924 delete ev->mThread;
4925 return true;
4926 }
4927#endif
4928
4929 case VBoxDefs::AsyncEventType:
4930 {
4931 VBoxAsyncEvent *ev = (VBoxAsyncEvent *) e;
4932 ev->handle();
4933 return true;
4934 }
4935
4936 case VBoxDefs::MediaEnumEventType:
4937 {
4938 VBoxMediaEnumEvent *ev = (VBoxMediaEnumEvent*) e;
4939
4940 if (!ev->mLast)
4941 {
4942 if (ev->mMedium.state() == KMediaState_Inaccessible &&
4943 !ev->mMedium.result().isOk())
4944 vboxProblem().cannotGetMediaAccessibility (ev->mMedium);
4945 Assert (mCurrentMediumIterator != mMediaList.end());
4946 *mCurrentMediumIterator = ev->mMedium;
4947 emit mediumEnumerated (*mCurrentMediumIterator);
4948 ++ mCurrentMediumIterator;
4949 }
4950 else
4951 {
4952 /* the thread has posted the last message, wait for termination */
4953 mMediaEnumThread->wait();
4954 delete mMediaEnumThread;
4955 mMediaEnumThread = 0;
4956 Assert (mCurrentMediumIterator == mMediaList.end());
4957 emit mediumEnumFinished (mMediaList);
4958 }
4959
4960 return true;
4961 }
4962
4963 /* VirtualBox callback events */
4964
4965 case VBoxDefs::MachineStateChangeEventType:
4966 {
4967 emit machineStateChanged (*(VBoxMachineStateChangeEvent *) e);
4968 return true;
4969 }
4970 case VBoxDefs::MachineDataChangeEventType:
4971 {
4972 emit machineDataChanged (*(VBoxMachineDataChangeEvent *) e);
4973 return true;
4974 }
4975 case VBoxDefs::MachineRegisteredEventType:
4976 {
4977 emit machineRegistered (*(VBoxMachineRegisteredEvent *) e);
4978 return true;
4979 }
4980 case VBoxDefs::SessionStateChangeEventType:
4981 {
4982 emit sessionStateChanged (*(VBoxSessionStateChangeEvent *) e);
4983 return true;
4984 }
4985 case VBoxDefs::SnapshotEventType:
4986 {
4987 emit snapshotChanged (*(VBoxSnapshotEvent *) e);
4988 return true;
4989 }
4990 case VBoxDefs::CanShowRegDlgEventType:
4991 {
4992 emit canShowRegDlg (((VBoxCanShowRegDlgEvent *) e)->mCanShow);
4993 return true;
4994 }
4995 case VBoxDefs::CanShowUpdDlgEventType:
4996 {
4997 emit canShowUpdDlg (((VBoxCanShowUpdDlgEvent *) e)->mCanShow);
4998 return true;
4999 }
5000 case VBoxDefs::ChangeGUILanguageEventType:
5001 {
5002 loadLanguage (static_cast<VBoxChangeGUILanguageEvent*> (e)->mLangId);
5003 return true;
5004 }
5005
5006 default:
5007 break;
5008 }
5009
5010 return QObject::event (e);
5011}
5012
5013bool VBoxGlobal::eventFilter (QObject *aObject, QEvent *aEvent)
5014{
5015 if (aEvent->type() == QEvent::LanguageChange &&
5016 aObject->isWidgetType() &&
5017 static_cast <QWidget *> (aObject)->isTopLevel())
5018 {
5019 /* Catch the language change event before any other widget gets it in
5020 * order to invalidate cached string resources (like the details view
5021 * templates) that may be used by other widgets. */
5022 QWidgetList list = QApplication::topLevelWidgets();
5023 if (list.first() == aObject)
5024 {
5025 /* call this only once per every language change (see
5026 * QApplication::installTranslator() for details) */
5027 retranslateUi();
5028 }
5029 }
5030
5031 return QObject::eventFilter (aObject, aEvent);
5032}
5033
5034// Private members
5035////////////////////////////////////////////////////////////////////////////////
5036
5037void VBoxGlobal::init()
5038{
5039#ifdef DEBUG
5040 verString += " [DEBUG]";
5041#endif
5042
5043#ifdef Q_WS_WIN
5044 /* COM for the main thread is initialized in main() */
5045#else
5046 HRESULT rc = COMBase::InitializeCOM();
5047 if (FAILED (rc))
5048 {
5049 vboxProblem().cannotInitCOM (rc);
5050 return;
5051 }
5052#endif
5053
5054 mVBox.createInstance (CLSID_VirtualBox);
5055 if (!mVBox.isOk())
5056 {
5057 vboxProblem().cannotCreateVirtualBox (mVBox);
5058 return;
5059 }
5060
5061 /* initialize guest OS type vector */
5062 CGuestOSTypeCollection coll = mVBox.GetGuestOSTypes();
5063 int osTypeCount = coll.GetCount();
5064 AssertMsg (osTypeCount > 0, ("Number of OS types must not be zero"));
5065 if (osTypeCount > 0)
5066 {
5067 vm_os_types.resize (osTypeCount);
5068 int i = 0;
5069 CGuestOSTypeEnumerator en = coll.Enumerate();
5070 while (en.HasMore())
5071 vm_os_types [i++] = en.GetNext();
5072 }
5073
5074 /* fill in OS type icon dictionary */
5075 static const char *kOSTypeIcons [][2] =
5076 {
5077 {"unknown", ":/os_unknown.png"},
5078 {"dos", ":/os_dos.png"},
5079 {"win31", ":/os_win31.png"},
5080 {"win95", ":/os_win95.png"},
5081 {"win98", ":/os_win98.png"},
5082 {"winme", ":/os_winme.png"},
5083 {"winnt4", ":/os_winnt4.png"},
5084 {"win2k", ":/os_win2k.png"},
5085 {"winxp", ":/os_winxp.png"},
5086 {"win2k3", ":/os_win2k3.png"},
5087 {"winvista", ":/os_winvista.png"},
5088 {"win2k8", ":/os_win2k8.png"},
5089 {"os2warp3", ":/os_os2warp3.png"},
5090 {"os2warp4", ":/os_os2warp4.png"},
5091 {"os2warp45", ":/os_os2warp45.png"},
5092 {"ecs", ":/os_ecs.png"},
5093 {"linux22", ":/os_linux22.png"},
5094 {"linux24", ":/os_linux24.png"},
5095 {"linux26", ":/os_linux26.png"},
5096 {"archlinux", ":/os_archlinux.png"},
5097 {"debian", ":/os_debian.png"},
5098 {"opensolaris", ":/os_opensolaris.png"},
5099 {"opensuse", ":/os_opensuse.png"},
5100 {"fedoracore", ":/os_fedoracore.png"},
5101 {"gentoo", ":/os_gentoo.png"},
5102 {"mandriva", ":/os_mandriva.png"},
5103 {"redhat", ":/os_redhat.png"},
5104 {"ubuntu", ":/os_ubuntu.png"},
5105 {"xandros", ":/os_xandros.png"},
5106 {"freebsd", ":/os_freebsd.png"},
5107 {"openbsd", ":/os_openbsd.png"},
5108 {"netbsd", ":/os_netbsd.png"},
5109 {"netware", ":/os_netware.png"},
5110 {"solaris", ":/os_solaris.png"},
5111 {"l4", ":/os_l4.png"},
5112 };
5113 for (uint n = 0; n < SIZEOF_ARRAY (kOSTypeIcons); n ++)
5114 {
5115 vm_os_type_icons.insert (kOSTypeIcons [n][0],
5116 new QPixmap (kOSTypeIcons [n][1]));
5117 }
5118
5119 /* fill in VM state icon dictionary */
5120 static struct
5121 {
5122 KMachineState state;
5123 const char *name;
5124 }
5125 vmStateIcons[] =
5126 {
5127 {KMachineState_Null, NULL},
5128 {KMachineState_PoweredOff, ":/state_powered_off_16px.png"},
5129 {KMachineState_Saved, ":/state_saved_16px.png"},
5130 {KMachineState_Aborted, ":/state_aborted_16px.png"},
5131 {KMachineState_Running, ":/state_running_16px.png"},
5132 {KMachineState_Paused, ":/state_paused_16px.png"},
5133 {KMachineState_Stuck, ":/state_stuck_16px.png"},
5134 {KMachineState_Starting, ":/state_running_16px.png"}, /// @todo (dmik) separate icon?
5135 {KMachineState_Stopping, ":/state_running_16px.png"}, /// @todo (dmik) separate icon?
5136 {KMachineState_Saving, ":/state_saving_16px.png"},
5137 {KMachineState_Restoring, ":/state_restoring_16px.png"},
5138 {KMachineState_Discarding, ":/state_discarding_16px.png"},
5139 {KMachineState_SettingUp, ":/settings_16px.png"},
5140 };
5141 for (uint n = 0; n < SIZEOF_ARRAY (vmStateIcons); n ++)
5142 {
5143 mStateIcons.insert (vmStateIcons [n].state,
5144 new QPixmap (vmStateIcons [n].name));
5145 }
5146
5147 /* online/offline snapshot icons */
5148 mOfflineSnapshotIcon = QPixmap (":/offline_snapshot_16px.png");
5149 mOnlineSnapshotIcon = QPixmap (":/online_snapshot_16px.png");
5150
5151 /* initialize state colors vector */
5152 vm_state_color.insert (KMachineState_Null, new QColor(Qt::red));
5153 vm_state_color.insert (KMachineState_PoweredOff, new QColor(Qt::gray));
5154 vm_state_color.insert (KMachineState_Saved, new QColor(Qt::yellow));
5155 vm_state_color.insert (KMachineState_Aborted, new QColor(Qt::darkRed));
5156 vm_state_color.insert (KMachineState_Running, new QColor(Qt::green));
5157 vm_state_color.insert (KMachineState_Paused, new QColor(Qt::darkGreen));
5158 vm_state_color.insert (KMachineState_Stuck, new QColor(Qt::darkMagenta));
5159 vm_state_color.insert (KMachineState_Starting, new QColor(Qt::green));
5160 vm_state_color.insert (KMachineState_Stopping, new QColor(Qt::green));
5161 vm_state_color.insert (KMachineState_Saving, new QColor(Qt::green));
5162 vm_state_color.insert (KMachineState_Restoring, new QColor(Qt::green));
5163 vm_state_color.insert (KMachineState_Discarding, new QColor(Qt::green));
5164 vm_state_color.insert (KMachineState_SettingUp, new QColor(Qt::green));
5165
5166 qApp->installEventFilter (this);
5167
5168 /* create default non-null global settings */
5169 gset = VBoxGlobalSettings (false);
5170
5171 /* try to load global settings */
5172 gset.load (mVBox);
5173 if (!mVBox.isOk() || !gset)
5174 {
5175 vboxProblem().cannotLoadGlobalConfig (mVBox, gset.lastError());
5176 return;
5177 }
5178
5179 /* Load customized language if any */
5180 QString languageId = gset.languageId();
5181 if (!languageId.isNull())
5182 loadLanguage (languageId);
5183
5184 retranslateUi();
5185
5186 /* process command line */
5187
5188 vm_render_mode_str = 0;
5189#ifdef VBOX_WITH_DEBUGGER_GUI
5190# ifdef VBOX_WITH_DEBUGGER_GUI_MENU
5191 mDbgEnabled = true;
5192# else
5193 mDbgEnabled = RTEnvExist("VBOX_GUI_DBG_ENABLED");
5194# endif
5195 mDbgAutoShow = RTEnvExist("VBOX_GUI_DBG_AUTO_SHOW");
5196#endif
5197
5198 int argc = qApp->argc();
5199 int i = 1;
5200 while (i < argc)
5201 {
5202 const char *arg = qApp->argv() [i];
5203 if ( !::strcmp (arg, "-startvm"))
5204 {
5205 if (++i < argc)
5206 {
5207 QString param = QString (qApp->argv() [i]);
5208 QUuid uuid = QUuid (param);
5209 if (!uuid.isNull())
5210 {
5211 vmUuid = uuid;
5212 }
5213 else
5214 {
5215 CMachine m = mVBox.FindMachine (param);
5216 if (m.isNull())
5217 {
5218 vboxProblem().cannotFindMachineByName (mVBox, param);
5219 return;
5220 }
5221 vmUuid = m.GetId();
5222 }
5223 }
5224 }
5225 else if (!::strcmp (arg, "-comment"))
5226 {
5227 ++i;
5228 }
5229 else if (!::strcmp (arg, "-rmode"))
5230 {
5231 if (++i < argc)
5232 vm_render_mode_str = qApp->argv() [i];
5233 }
5234#ifdef VBOX_WITH_DEBUGGER_GUI
5235 else if (!::strcmp (arg, "-dbg") || !::strcmp (arg, "--dbg"))
5236 {
5237 mDbgEnabled = true;
5238 }
5239 else if (!::strcmp( arg, "-debug") || !::strcmp( arg, "--debug"))
5240 {
5241 mDbgEnabled = true;
5242 mDbgAutoShow = true;
5243 }
5244 else if (!::strcmp (arg, "-no-debug") || !::strcmp (arg, "--no-debug"))
5245 {
5246 mDbgEnabled = false;
5247 mDbgAutoShow = false;
5248 }
5249#endif
5250 /** @todo add an else { msgbox(syntax error); exit(1); } here, pretty please... */
5251 i++;
5252 }
5253
5254 vm_render_mode = vboxGetRenderMode( vm_render_mode_str );
5255
5256 /* setup the callback */
5257 callback = CVirtualBoxCallback (new VBoxCallback (*this));
5258 mVBox.RegisterCallback (callback);
5259 AssertWrapperOk (mVBox);
5260 if (!mVBox.isOk())
5261 return;
5262
5263#ifdef VBOX_WITH_DEBUGGER_GUI
5264 /* setup the debugger gui. */
5265 if (RTEnvExist("VBOX_GUI_NO_DEBUGGER"))
5266 mDbgEnabled = mDbgAutoShow = false;
5267 if (mDbgEnabled)
5268 {
5269 int rc = SUPR3HardenedLdrLoadAppPriv("VBoxDbg", &mhVBoxDbg);
5270 if (RT_FAILURE(rc))
5271 {
5272 mhVBoxDbg = NIL_RTLDRMOD;
5273 mDbgAutoShow = false;
5274 LogRel(("Failed to load VBoxDbg, rc=%Rrc\n", rc));
5275 }
5276 }
5277#endif
5278
5279 mValid = true;
5280}
5281
5282/** @internal
5283 *
5284 * This method should be never called directly. It is called automatically
5285 * when the application terminates.
5286 */
5287void VBoxGlobal::cleanup()
5288{
5289 /* sanity check */
5290 if (!sVBoxGlobalInCleanup)
5291 {
5292 AssertMsgFailed (("Should never be called directly\n"));
5293 return;
5294 }
5295
5296 if (!callback.isNull())
5297 {
5298 mVBox.UnregisterCallback (callback);
5299 AssertWrapperOk (mVBox);
5300 callback.detach();
5301 }
5302
5303 if (mMediaEnumThread)
5304 {
5305 /* sVBoxGlobalInCleanup is true here, so just wait for the thread */
5306 mMediaEnumThread->wait();
5307 delete mMediaEnumThread;
5308 mMediaEnumThread = 0;
5309 }
5310
5311#ifdef VBOX_WITH_REGISTRATION
5312 if (mRegDlg)
5313 mRegDlg->close();
5314#endif
5315
5316 if (mConsoleWnd)
5317 delete mConsoleWnd;
5318 if (mSelectorWnd)
5319 delete mSelectorWnd;
5320
5321 /* ensure CGuestOSType objects are no longer used */
5322 vm_os_types.clear();
5323 /* media list contains a lot of CUUnknown, release them */
5324 mMediaList.clear();
5325 mCurrentMediumIterator = mMediaList.end();
5326 /* the last step to ensure we don't use COM any more */
5327 mVBox.detach();
5328
5329 /* There may be VBoxMediaEnumEvent instances still in the message
5330 * queue which reference COM objects. Remove them to release those objects
5331 * before uninitializing the COM subsystem. */
5332 QApplication::removePostedEvents (this);
5333
5334#ifdef Q_WS_WIN
5335 /* COM for the main thread is shutdown in main() */
5336#else
5337 COMBase::CleanupCOM();
5338#endif
5339
5340 mValid = false;
5341}
5342
5343/** @fn vboxGlobal
5344 *
5345 * Shortcut to the static VBoxGlobal::instance() method, for convenience.
5346 */
5347
5348
5349/**
5350 * USB Popup Menu class methods
5351 * This class provides the list of USB devices attached to the host.
5352 */
5353VBoxUSBMenu::VBoxUSBMenu (QWidget *aParent) : QMenu (aParent)
5354{
5355 connect (this, SIGNAL (aboutToShow()),
5356 this, SLOT (processAboutToShow()));
5357// connect (this, SIGNAL (hovered (QAction *)),
5358// this, SLOT (processHighlighted (QAction *)));
5359}
5360
5361const CUSBDevice& VBoxUSBMenu::getUSB (QAction *aAction)
5362{
5363 return mUSBDevicesMap [aAction];
5364}
5365
5366void VBoxUSBMenu::setConsole (const CConsole &aConsole)
5367{
5368 mConsole = aConsole;
5369}
5370
5371void VBoxUSBMenu::processAboutToShow()
5372{
5373 clear();
5374 mUSBDevicesMap.clear();
5375
5376 CHost host = vboxGlobal().virtualBox().GetHost();
5377
5378 bool isUSBEmpty = host.GetUSBDevices().GetCount() == 0;
5379 if (isUSBEmpty)
5380 {
5381 QAction *action = addAction (tr ("<no available devices>", "USB devices"));
5382 action->setEnabled (false);
5383 action->setToolTip (tr ("No supported devices connected to the host PC",
5384 "USB device tooltip"));
5385 }
5386 else
5387 {
5388 CHostUSBDeviceEnumerator en = host.GetUSBDevices().Enumerate();
5389 while (en.HasMore())
5390 {
5391 CHostUSBDevice dev = en.GetNext();
5392 CUSBDevice usb (dev);
5393 QAction *action = addAction (vboxGlobal().details (usb));
5394 action->setCheckable (true);
5395 mUSBDevicesMap [action] = usb;
5396 /* check if created item was alread attached to this session */
5397 if (!mConsole.isNull())
5398 {
5399 CUSBDevice attachedUSB =
5400 mConsole.GetUSBDevices().FindById (usb.GetId());
5401 action->setChecked (!attachedUSB.isNull());
5402 action->setEnabled (dev.GetState() !=
5403 KUSBDeviceState_Unavailable);
5404 }
5405 }
5406 }
5407}
5408
5409bool VBoxUSBMenu::event(QEvent *aEvent)
5410{
5411 /* We provide dynamic tooltips for the usb devices */
5412 if (aEvent->type() == QEvent::ToolTip)
5413 {
5414 QHelpEvent *helpEvent = static_cast<QHelpEvent *> (aEvent);
5415 QAction *action = actionAt (helpEvent->pos());
5416 if (action)
5417 {
5418 CUSBDevice usb = mUSBDevicesMap [action];
5419 if (!usb.isNull())
5420 {
5421 QToolTip::showText (helpEvent->globalPos(), vboxGlobal().toolTip (usb));
5422 return true;
5423 }
5424 }
5425 }
5426 return QMenu::event (aEvent);
5427}
5428
5429/**
5430 * Enable/Disable Menu class.
5431 * This class provides enable/disable menu items.
5432 */
5433VBoxSwitchMenu::VBoxSwitchMenu (QWidget *aParent, QAction *aAction,
5434 bool aInverted)
5435 : QMenu (aParent), mAction (aAction), mInverted (aInverted)
5436{
5437 /* this menu works only with toggle action */
5438 Assert (aAction->isCheckable());
5439 addAction(aAction);
5440 connect (this, SIGNAL (aboutToShow()),
5441 this, SLOT (processAboutToShow()));
5442}
5443
5444void VBoxSwitchMenu::setToolTip (const QString &aTip)
5445{
5446 mAction->setToolTip (aTip);
5447}
5448
5449void VBoxSwitchMenu::processAboutToShow()
5450{
5451 QString text = mAction->isChecked() ^ mInverted ? tr ("Disable") : tr ("Enable");
5452 mAction->setText (text);
5453}
5454
Note: See TracBrowser for help on using the repository browser.

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