Beispiel #1
0
bool UINewVMWzdPage2::createMachineFolder()
{
    /* Cleanup old folder if present: */
    bool fMachineFolderDeleted = cleanupMachineFolder();
    if (!fMachineFolderDeleted)
    {
        msgCenter().warnAboutCannotCreateMachineFolder(this, m_strMachineFolder);
        return false;
    }

    /* Get VBox: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    /* Get default machines directory: */
    QString strDefaultMachinesFolder = vbox.GetSystemProperties().GetDefaultMachineFolder();
    /* Compose machine filename name: */
    QString strMachineFilename = vbox.ComposeMachineFilename(field("name").toString(), strDefaultMachinesFolder);
    QFileInfo fileInfo(strMachineFilename);
    /* Get machine directory: */
    QString strMachineFolder = fileInfo.absolutePath();

    /* Try to create this machine directory (and it's predecessors): */
    bool fMachineFolderCreated = QDir().mkpath(strMachineFolder);
    if (!fMachineFolderCreated)
    {
        msgCenter().warnAboutCannotCreateMachineFolder(this, strMachineFolder);
        return false;
    }

    /* Initialize machine dir value: */
    m_strMachineFolder = strMachineFolder;
    return true;
}
/* Adds new network interface: */
void UIGlobalSettingsNetwork::sltAddInterface()
{
    /* Prepare useful variables: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    CHost host = vboxGlobal().host();

    /* Create new host-only interface: */
    CHostNetworkInterface iface;
    CProgress progress = host.CreateHostOnlyNetworkInterface(iface);
    if (host.isOk())
    {
        msgCenter().showModalProgressDialog(progress, tr("Networking"),
                                              ":/nw_32px.png", this, true, 0);
        if (progress.GetResultCode() == 0)
        {
            /* Create DHCP server: */
            CDHCPServer dhcp = vbox.FindDHCPServerByNetworkName(iface.GetNetworkName());
            if (dhcp.isNull())
            {
                vbox.CreateDHCPServer(iface.GetNetworkName());
                dhcp = vbox.FindDHCPServerByNetworkName(iface.GetNetworkName());
            }
            AssertMsg(!dhcp.isNull(), ("DHCP server creation failed!\n"));

            /* Append cache with new item: */
            appendCacheItem(iface);
            /* Append list with new item: */
            appendListItem(m_cache.m_items.last(), true);
        }
        else
            msgCenter().cannotCreateHostInterface(progress, this);
    }
    else
        msgCenter().cannotCreateHostInterface(host, this);
}
/* static */
QStringList UIMachineSettingsNetworkPage::otherGenericDriverList()
{
    /* Load total generic driver list of all VMs: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    QStringList otherGenericDrivers(QList<QString>::fromVector(vbox.GetGenericNetworkDrivers()));
    return otherGenericDrivers;
}
/* static */
QStringList UIMachineSettingsNetworkPage::otherInternalNetworkList()
{
    /* Load total internal network list of all VMs: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    QStringList otherInternalNetworks(QList<QString>::fromVector(vbox.GetInternalNetworks()));
    return otherInternalNetworks;
}
Beispiel #5
0
/* static */
bool UIWizardFirstRun::isBootHardDiskAttached(const CMachine &machine)
{
    /* Result is 'false' initially: */
    bool fIsBootHardDiskAttached = false;
    /* Get 'vbox' global object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    /* Determine machine 'OS type': */
    const CGuestOSType &osType = vbox.GetGuestOSType(machine.GetOSTypeId());
    /* Determine recommended controller's 'bus' & 'type': */
    KStorageBus hdCtrBus = osType.GetRecommendedHDStorageBus();
    KStorageControllerType hdCtrType = osType.GetRecommendedHDStorageController();
    /* Enumerate attachments vector: */
    const CMediumAttachmentVector &attachments = machine.GetMediumAttachments();
    for (int i = 0; i < attachments.size(); ++i)
    {
        /* Get current attachment: */
        const CMediumAttachment &attachment = attachments[i];
        /* Determine attachment's controller: */
        const CStorageController &controller = machine.GetStorageControllerByName(attachment.GetController());
        /* If controller's 'bus' & 'type' are recommended and attachment's 'type' is 'hard disk': */
        if (controller.GetBus() == hdCtrBus &&
            controller.GetControllerType() == hdCtrType &&
            attachment.GetType() == KDeviceType_HardDisk)
        {
            /* Set the result to 'true': */
            fIsBootHardDiskAttached = true;
            break;
        }
    }
    /* Return result: */
    return fIsBootHardDiskAttached;
}
Beispiel #6
0
bool UIWizardCloneVD::copyVirtualDisk()
{
    /* Gather attributes: */
    CMedium sourceVirtualDisk = field("sourceVirtualDisk").value<CMedium>();
    CMediumFormat mediumFormat = field("mediumFormat").value<CMediumFormat>();
    qulonglong uVariant = field("mediumVariant").toULongLong();
    QString strMediumPath = field("mediumPath").toString();
    qulonglong uSize = field("mediumSize").toULongLong();
    /* Check attributes: */
    AssertReturn(!strMediumPath.isNull(), false);
    AssertReturn(uSize > 0, false);

    /* Get VBox object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();

    /* Create new virtual hard-disk: */
    CMedium virtualDisk = vbox.CreateHardDisk(mediumFormat.GetName(), strMediumPath);
    if (!vbox.isOk())
    {
        msgCenter().cannotCreateHardDiskStorage(vbox, strMediumPath, this);
        return false;
    }

    /* Compose medium-variant: */
    QVector<KMediumVariant> variants(sizeof(qulonglong)*8);
    for (int i = 0; i < variants.size(); ++i)
    {
        qulonglong temp = uVariant;
        temp &= 1<<i;
        variants[i] = (KMediumVariant)temp;
    }

    /* Copy existing virtual-disk to the new virtual-disk: */
    CProgress progress = sourceVirtualDisk.CloneTo(virtualDisk, variants, CMedium());
    if (!sourceVirtualDisk.isOk())
    {
        msgCenter().cannotCreateHardDiskStorage(sourceVirtualDisk, strMediumPath, this);
        return false;
    }

    /* Show creation progress: */
    msgCenter().showModalProgressDialog(progress, windowTitle(), ":/progress_media_create_90px.png", this);
    if (progress.GetCanceled())
        return false;
    if (!progress.isOk() || progress.GetResultCode() != 0)
    {
        msgCenter().cannotCreateHardDiskStorage(progress, strMediumPath, this);
        return false;
    }

    /* Remember created virtual-disk: */
    m_virtualDisk = virtualDisk;

    /* Just close the created medium, it is not necessary yet: */
    m_virtualDisk.Close();

    return true;
}
Beispiel #7
0
bool UIWizardNewVD::createVirtualDisk()
{
    /* Gather attributes: */
    CMediumFormat mediumFormat = field("mediumFormat").value<CMediumFormat>();
    qulonglong uVariant = field("mediumVariant").toULongLong();
    QString strMediumPath = field("mediumPath").toString();
    qulonglong uSize = field("mediumSize").toULongLong();
    /* Check attributes: */
    AssertReturn(!strMediumPath.isNull(), false);
    AssertReturn(uSize > 0, false);

    /* Get VBox object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();

    /* Create new virtual hard-disk: */
    CMedium virtualDisk = vbox.CreateMedium(mediumFormat.GetName(), strMediumPath, KAccessMode_ReadWrite, KDeviceType_HardDisk);
    if (!vbox.isOk())
    {
        msgCenter().cannotCreateHardDiskStorage(vbox, strMediumPath, this);
        return false;
    }

    /* Compose medium-variant: */
    QVector<KMediumVariant> variants(sizeof(qulonglong)*8);
    for (int i = 0; i < variants.size(); ++i)
    {
        qulonglong temp = uVariant;
        temp &= UINT64_C(1)<<i;
        variants[i] = (KMediumVariant)temp;
    }

    /* Create base storage for the new virtual-disk: */
    CProgress progress = virtualDisk.CreateBaseStorage(uSize, variants);
    if (!virtualDisk.isOk())
    {
        msgCenter().cannotCreateHardDiskStorage(virtualDisk, strMediumPath, this);
        return false;
    }

    /* Show creation progress: */
    msgCenter().showModalProgressDialog(progress, windowTitle(), ":/progress_media_create_90px.png", this);
    if (progress.GetCanceled())
        return false;
    if (!progress.isOk() || progress.GetResultCode() != 0)
    {
        msgCenter().cannotCreateHardDiskStorage(progress, strMediumPath, this);
        return false;
    }

    /* Remember created virtual-disk: */
    m_virtualDisk = virtualDisk;

    /* Inform VBoxGlobal about it: */
    vboxGlobal().createMedium(UIMedium(m_virtualDisk, UIMediumType_HardDisk, KMediumState_Created));

    return true;
}
void UIHostNetworkManagerWidget::loadHostNetwork(const CHostNetworkInterface &comInterface, UIDataHostNetwork &data)
{
    /* Gather interface settings: */
    if (comInterface.isOk())
        data.m_interface.m_strName = comInterface.GetName();
    if (comInterface.isOk())
        data.m_interface.m_fDHCPEnabled = comInterface.GetDHCPEnabled();
    if (comInterface.isOk())
        data.m_interface.m_strAddress = comInterface.GetIPAddress();
    if (comInterface.isOk())
        data.m_interface.m_strMask = comInterface.GetNetworkMask();
    if (comInterface.isOk())
        data.m_interface.m_fSupportedIPv6 = comInterface.GetIPV6Supported();
    if (comInterface.isOk())
        data.m_interface.m_strAddress6 = comInterface.GetIPV6Address();
    if (comInterface.isOk())
        data.m_interface.m_strPrefixLength6 = QString::number(comInterface.GetIPV6NetworkMaskPrefixLength());

    /* Get host interface network name for further activities: */
    QString strNetworkName;
    if (comInterface.isOk())
        strNetworkName = comInterface.GetNetworkName();

    /* Show error message if necessary: */
    if (!comInterface.isOk())
        msgCenter().cannotAcquireHostNetworkInterfaceParameter(comInterface, this);

    /* Get VBox for further activities: */
    CVirtualBox comVBox = vboxGlobal().virtualBox();

    /* Find corresponding DHCP server (create if necessary): */
    CDHCPServer comServer = comVBox.FindDHCPServerByNetworkName(strNetworkName);
    if (!comVBox.isOk() || comServer.isNull())
        comServer = comVBox.CreateDHCPServer(strNetworkName);

    /* Show error message if necessary: */
    if (!comVBox.isOk() || comServer.isNull())
        msgCenter().cannotCreateDHCPServer(comVBox, strNetworkName, this);
    else
    {
        /* Gather DHCP server settings: */
        if (comServer.isOk())
            data.m_dhcpserver.m_fEnabled = comServer.GetEnabled();
        if (comServer.isOk())
            data.m_dhcpserver.m_strAddress = comServer.GetIPAddress();
        if (comServer.isOk())
            data.m_dhcpserver.m_strMask = comServer.GetNetworkMask();
        if (comServer.isOk())
            data.m_dhcpserver.m_strLowerAddress = comServer.GetLowerIP();
        if (comServer.isOk())
            data.m_dhcpserver.m_strUpperAddress = comServer.GetUpperIP();

        /* Show error message if necessary: */
        if (!comServer.isOk())
            return msgCenter().cannotAcquireDHCPServerParameter(comServer, this);
    }
}
CAppliance* UIApplianceExportEditorWidget::init()
{
    if (m_pAppliance)
        delete m_pAppliance;
    CVirtualBox vbox = vboxGlobal().virtualBox();
    /* Create a appliance object */
    m_pAppliance = new CAppliance(vbox.CreateAppliance());
//    bool fResult = m_pAppliance->isOk();
    return m_pAppliance;
}
/**
 *  Saves the settings to the (global) extra data area of VirtualBox.
 *
 *  If an error occurs while accessing extra data area, the method immediately
 *  returns and the vbox argument will hold all error info (and therefore
 *  vbox.isOk() will be false to indicate this).
 */
void VBoxGlobalSettings::save (CVirtualBox &vbox) const
{
    for (size_t i = 0; i < SIZEOF_ARRAY (gPropertyMap); i++)
    {
        QVariant value = property (gPropertyMap [i].name);
        Assert (value.isValid() && value.canConvert (QVariant::String));

        vbox.SetExtraData (gPropertyMap [i].publicName, value.toString());
        if (!vbox.isOk())
            return;
    }
}
void UIHostNetworkManagerWidget::sltCreateHostNetwork()
{
    /* Get host for further activities: */
    CHost comHost = vboxGlobal().host();

    /* Create interface: */
    CHostNetworkInterface comInterface;
    CProgress progress = comHost.CreateHostOnlyNetworkInterface(comInterface);

    /* Show error message if necessary: */
    if (!comHost.isOk() || progress.isNull())
        msgCenter().cannotCreateHostNetworkInterface(comHost, this);
    else
    {
        /* Show interface creation progress: */
        msgCenter().showModalProgressDialog(progress, UIHostNetworkManager::tr("Adding network..."), ":/progress_network_interface_90px.png", this, 0);

        /* Show error message if necessary: */
        if (!progress.isOk() || progress.GetResultCode() != 0)
            msgCenter().cannotCreateHostNetworkInterface(progress, this);
        else
        {
            /* Get network name for further activities: */
            const QString strNetworkName = comInterface.GetNetworkName();

            /* Show error message if necessary: */
            if (!comInterface.isOk())
                msgCenter().cannotAcquireHostNetworkInterfaceParameter(comInterface, this);
            else
            {
                /* Get VBox for further activities: */
                CVirtualBox comVBox = vboxGlobal().virtualBox();

                /* Find corresponding DHCP server (create if necessary): */
                CDHCPServer comServer = comVBox.FindDHCPServerByNetworkName(strNetworkName);
                if (!comVBox.isOk() || comServer.isNull())
                    comServer = comVBox.CreateDHCPServer(strNetworkName);

                /* Show error message if necessary: */
                if (!comVBox.isOk() || comServer.isNull())
                    msgCenter().cannotCreateDHCPServer(comVBox, strNetworkName, this);
            }

            /* Add interface to the tree: */
            UIDataHostNetwork data;
            loadHostNetwork(comInterface, data);
            createItemForNetworkHost(data, true);

            /* Adjust tree-widget: */
            sltAdjustTreeWidget();
        }
    }
}
Beispiel #12
0
bool UIWizardNewVD::createVirtualDisk()
{
    /* Gather attributes: */
    CMediumFormat mediumFormat = field("mediumFormat").value<CMediumFormat>();
    qulonglong uVariant = field("mediumVariant").toULongLong();
    QString strMediumPath = field("mediumPath").toString();
    qulonglong uSize = field("mediumSize").toULongLong();
    /* Check attributes: */
    AssertReturn(!strMediumPath.isNull(), false);
    AssertReturn(uSize > 0, false);

    /* Get vbox object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();

    /* Create new virtual disk: */
    CMedium virtualDisk = vbox.CreateHardDisk(mediumFormat.GetName(), strMediumPath);
    CProgress progress;
    if (!vbox.isOk())
    {
        msgCenter().cannotCreateHardDiskStorage(this, vbox, strMediumPath, virtualDisk, progress);
        return false;
    }

    /* Create base storage for the new hard disk: */
    progress = virtualDisk.CreateBaseStorage(uSize, uVariant);
    if (!virtualDisk.isOk())
    {
        msgCenter().cannotCreateHardDiskStorage(this, vbox, strMediumPath, virtualDisk, progress);
        return false;
    }

    /* Show creation progress: */
    msgCenter().showModalProgressDialog(progress, windowTitle(), ":/progress_media_create_90px.png", this, true);
    if (progress.GetCanceled())
        return false;
    if (!progress.isOk() || progress.GetResultCode() != 0)
    {
        msgCenter().cannotCreateHardDiskStorage(this, vbox, strMediumPath, virtualDisk, progress);
        return false;
    }

    /* Remember created virtual-disk: */
    m_virtualDisk = virtualDisk;

    /* Inform everybody there is a new medium: */
    vboxGlobal().addMedium(UIMedium(m_virtualDisk, UIMediumType_HardDisk, KMediumState_Created));

    return true;
}
/* Save data from cache to corresponding external object(s),
 * this task COULD be performed in other than GUI thread: */
void UIMachineSettingsGeneral::saveFromCacheTo(QVariant &data)
{
    /* Fetch data to machine: */
    UISettingsPageMachine::fetchData(data);

    /* Check if general data was changed: */
    if (m_cache.wasChanged())
    {
        /* Get general data from cache: */
        const UIDataSettingsMachineGeneral &generalData = m_cache.data();

        /* Store general data: */
        if (isMachineInValidMode())
        {
            /* Advanced tab: */
            m_machine.SetClipboardMode(generalData.m_clipboardMode);
            m_machine.SetDragAndDropMode(generalData.m_dragAndDropMode);
            m_machine.SetExtraData(GUI_SaveMountedAtRuntime, generalData.m_fSaveMountedAtRuntime ? "yes" : "no");
            m_machine.SetExtraData(GUI_ShowMiniToolBar, generalData.m_fShowMiniToolBar ? "yes" : "no");
            m_machine.SetExtraData(GUI_MiniToolBarAlignment, generalData.m_fMiniToolBarAtTop ? "top" : "bottom");
            /* Description tab: */
            m_machine.SetDescription(generalData.m_strDescription);
        }
        if (isMachineOffline())
        {
            /* Basic tab: Must update long mode CPU feature bit when os type changes. */
            if (generalData.m_strGuestOsTypeId != m_cache.base().m_strGuestOsTypeId)
            {
                m_machine.SetOSTypeId(generalData.m_strGuestOsTypeId);

                CVirtualBox vbox = vboxGlobal().virtualBox();
                CGuestOSType newType = vbox.GetGuestOSType(generalData.m_strGuestOsTypeId);
                m_machine.SetCPUProperty(KCPUPropertyType_LongMode, newType.GetIs64Bit());
            }

            /* Advanced tab: */
            m_machine.SetSnapshotFolder(generalData.m_strSnapshotsFolder);
            /* Basic (again) tab: */
            /* VM name must be last as otherwise its VM rename magic can collide with other settings in the config,
             * especially with the snapshot folder: */
            m_machine.SetName(generalData.m_strName);
        }
    }

    /* Upload machine to data: */
    UISettingsPageMachine::uploadData(data);
}
bool UIFirstRunWzdPage3::insertDevice()
{
    /* Get 'vbox' global object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    /* Determine machine 'OS type': */
    const CGuestOSType &osType = vbox.GetGuestOSType(m_Machine.GetOSTypeId());
    /* Determine recommended controller's 'bus' & 'type': */
    KStorageBus dvdCtrBus = osType.GetRecommendedDvdStorageBus();
    KStorageControllerType dvdCtrType = osType.GetRecommendedDvdStorageController();
    /* Declare null 'dvd' attachment: */
    CMediumAttachment cda;
    /* Enumerate attachments vector: */
    const CMediumAttachmentVector &attachments = m_Machine.GetMediumAttachments();
    for (int i = 0; i < attachments.size(); ++i)
    {
        /* Get current attachment: */
        const CMediumAttachment &attachment = attachments[i];
        /* Determine attachment's controller: */
        const CStorageController &controller = m_Machine.GetStorageControllerByName(attachment.GetController());
        /* If controller's 'bus' & 'type' are recommended and attachment's 'type' is 'dvd': */
        if (controller.GetBus() == dvdCtrBus &&
            controller.GetControllerType() == dvdCtrType &&
            attachment.GetType() == KDeviceType_DVD)
        {
            /* Remember attachment: */
            cda = attachment;
            break;
        }
    }
    AssertMsg(!cda.isNull(), ("Storage Controller is NOT properly configured!\n"));
    /* Get chosen 'dvd' medium to mount: */
    QString mediumId = field("id").toString();
    VBoxMedium vmedium = vboxGlobal().findMedium(mediumId);
    CMedium medium = vmedium.medium();              // @todo r=dj can this be cached somewhere?
    /* Mount medium to the predefined port/device: */
    m_Machine.MountMedium(cda.GetController(), cda.GetPort(), cda.GetDevice(), medium, false /* force */);
    if (m_Machine.isOk())
        return true;
    else
    {
        msgCenter().cannotRemountMedium(this, m_Machine, vmedium,
                                          true /* mount? */, false /* retry? */);
        return false;
    }
}
Beispiel #15
0
/* Removes selected network interface: */
void UIGlobalSettingsNetwork::sltDelInterface()
{
    /* Get interface item: */
    UIHostInterfaceItem *pItem = static_cast<UIHostInterfaceItem*>(m_pInterfacesTree->currentItem());
    AssertMsg(pItem, ("Current item should present!\n"));
    /* Get interface name: */
    QString strInterfaceName(pItem->name());
    /* Asking user about deleting selected network interface: */
    if (msgCenter().confirmDeletingHostInterface(strInterfaceName, this) == QIMessageBox::Cancel)
        return;

    /* Prepare useful variables: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    CHost host = vboxGlobal().host();

    /* Find corresponding interface: */
    const CHostNetworkInterface &iface = host.FindHostNetworkInterfaceByName(strInterfaceName);

    /* Remove DHCP server first: */
    CDHCPServer dhcp = vboxGlobal().virtualBox().FindDHCPServerByNetworkName(iface.GetNetworkName());
    if (!dhcp.isNull())
        vbox.RemoveDHCPServer(dhcp);

    /* Remove interface finally: */
    CProgress progress = host.RemoveHostOnlyNetworkInterface(iface.GetId());
    if (host.isOk())
    {
        msgCenter().showModalProgressDialog(progress, tr("Networking"),
                                              ":/nw_32px.png", this, true, 0);
        if (progress.GetResultCode() == 0)
        {
            /* Remove list item: */
            removeListItem(pItem);
            /* Remove cache item: */
            removeCacheItem(strInterfaceName);
        }
        else
            msgCenter().cannotRemoveHostInterface(progress, iface, this);
    }
    else
        msgCenter().cannotRemoveHostInterface(host, iface, this);
}
/**
 *  Loads the settings from the (global) extra data area of VirtualBox.
 *
 *  If an error occurs while accessing extra data area, the method immediately
 *  returns and the vbox argument will hold all error info (and therefore
 *  vbox.isOk() will be false to indicate this).
 *
 *  If an error occurs while setting the value of some property, the method
 *  also returns immediately. #operator !() will return false in this case
 *  and #lastError() will contain the error message.
 *
 *  @note   This method emits the #propertyChanged() signal.
 */
void VBoxGlobalSettings::load (CVirtualBox &vbox)
{
    for (size_t i = 0; i < SIZEOF_ARRAY(gPropertyMap); i++)
    {
        QString value = vbox.GetExtraData(gPropertyMap[i].publicName);
        if (!vbox.isOk())
            return;
        /* Check for the host key upgrade path. */
        if (   value.isEmpty()
            && QString(gPropertyMap[i].publicName) == "GUI/Input/HostKeyCombination")
            value = vbox.GetExtraData("GUI/Input/HostKey");
        /* Empty value means the key is absent. It is OK, the default will
         * apply. */
        if (value.isEmpty())
            continue;
        /* Try to set the property validating it against rx. */
        setPropertyPrivate(i, value);
        if (!(*this))
            break;
    }
}
QList<QPair<QString, QString> > UIMediumDefs::MediumBackends(const CVirtualBox &comVBox, KDeviceType enmType)
{
    /* Prepare a list of pairs with the form <tt>{"Backend Name", "*.suffix1 .suffix2 ..."}</tt>. */
    const CSystemProperties comSystemProperties = comVBox.GetSystemProperties();
    QVector<CMediumFormat> mediumFormats = comSystemProperties.GetMediumFormats();
    QList<QPair<QString, QString> > backendPropList;
    for (int i = 0; i < mediumFormats.size(); ++i)
    {
        /* Acquire file extensions & device types: */
        QVector<QString> fileExtensions;
        QVector<KDeviceType> deviceTypes;
        mediumFormats[i].DescribeFileExtensions(fileExtensions, deviceTypes);

        /* Compose filters list: */
        QStringList filters;
        for (int iExtensionIndex = 0; iExtensionIndex < fileExtensions.size(); ++iExtensionIndex)
            if (deviceTypes[iExtensionIndex] == enmType)
                filters << QString("*.%1").arg(fileExtensions[iExtensionIndex]);
        /* Create a pair out of the backend description and all suffix's. */
        if (!filters.isEmpty())
            backendPropList << QPair<QString, QString>(mediumFormats[i].GetName(), filters.join(" "));
    }
    return backendPropList;
}
void UIHostNetworkManagerWidget::sltRemoveHostNetwork()
{
    /* Get network item: */
    UIItemHostNetwork *pItem = static_cast<UIItemHostNetwork*>(m_pTreeWidget->currentItem());
    AssertMsgReturnVoid(pItem, ("Current item must not be null!\n"));

    /* Get interface name: */
    const QString strInterfaceName(pItem->name());

    /* Confirm host network removal: */
    if (!msgCenter().confirmHostOnlyInterfaceRemoval(strInterfaceName, this))
        return;

    /* Get host for further activities: */
    CHost comHost = vboxGlobal().host();

    /* Find corresponding interface: */
    const CHostNetworkInterface &comInterface = comHost.FindHostNetworkInterfaceByName(strInterfaceName);

    /* Show error message if necessary: */
    if (!comHost.isOk() || comInterface.isNull())
        msgCenter().cannotFindHostNetworkInterface(comHost, strInterfaceName, this);
    else
    {
        /* Get network name for further activities: */
        QString strNetworkName;
        if (comInterface.isOk())
            strNetworkName = comInterface.GetNetworkName();
        /* Get interface id for further activities: */
        QUuid uInterfaceId;
        if (comInterface.isOk())
            uInterfaceId = comInterface.GetId();

        /* Show error message if necessary: */
        if (!comInterface.isOk())
            msgCenter().cannotAcquireHostNetworkInterfaceParameter(comInterface, this);
        else
        {
            /* Get VBox for further activities: */
            CVirtualBox comVBox = vboxGlobal().virtualBox();

            /* Find corresponding DHCP server: */
            const CDHCPServer &comServer = comVBox.FindDHCPServerByNetworkName(strNetworkName);
            if (comVBox.isOk() && comServer.isNotNull())
            {
                /* Remove server if any: */
                comVBox.RemoveDHCPServer(comServer);

                /* Show error message if necessary: */
                if (!comVBox.isOk())
                    msgCenter().cannotRemoveDHCPServer(comVBox, strInterfaceName, this);
            }

            /* Remove interface finally: */
            CProgress progress = comHost.RemoveHostOnlyNetworkInterface(uInterfaceId);

            /* Show error message if necessary: */
            if (!comHost.isOk() || progress.isNull())
                msgCenter().cannotRemoveHostNetworkInterface(comHost, strInterfaceName, this);
            else
            {
                /* Show interface removal progress: */
                msgCenter().showModalProgressDialog(progress, UIHostNetworkManager::tr("Removing network..."), ":/progress_network_interface_90px.png", this, 0);

                /* Show error message if necessary: */
                if (!progress.isOk() || progress.GetResultCode() != 0)
                    return msgCenter().cannotRemoveHostNetworkInterface(progress, strInterfaceName, this);
                else
                {
                    /* Remove interface from the tree: */
                    delete pItem;

                    /* Adjust tree-widget: */
                    sltAdjustTreeWidget();
                }
            }
        }
    }
}
Beispiel #19
0
bool UIWizardNewVM::createVM()
{
    /* Get VBox object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();

    /* OS type: */
    CGuestOSType type = field("type").value<CGuestOSType>();
    QString strTypeId = type.GetId();

    /* Create virtual machine: */
    if (m_machine.isNull())
    {
        QVector<QString> groups;
        if (!m_strGroup.isEmpty())
            groups << m_strGroup;
        m_machine = vbox.CreateMachine(field("machineFilePath").toString(),
                                       field("machineBaseName").toString(),
                                       groups, strTypeId, QString());
        if (!vbox.isOk())
        {
            msgCenter().cannotCreateMachine(vbox, this);
            return false;
        }

        /* The First RUN Wizard is to be shown:
         * 1. if we don't attach any virtual hard-drive
         * 2. or attach a new (empty) one.
         * Usually we are assigning extra-data values through UIExtraDataManager,
         * but in that special case VM was not registered yet, so UIExtraDataManager is unaware of it. */
        if (field("virtualDiskId").toString().isNull() || !field("virtualDisk").value<CMedium>().isNull())
            m_machine.SetExtraData(GUI_FirstRun, "yes");
    }

    /* RAM size: */
    m_machine.SetMemorySize(field("ram").toInt());

    /* VRAM size - select maximum between recommended and minimum for fullscreen: */
    m_machine.SetVRAMSize(qMax(type.GetRecommendedVRAM(), (ULONG)(VBoxGlobal::requiredVideoMemory(strTypeId) / _1M)));

    /* Selecting recommended chipset type: */
    m_machine.SetChipsetType(type.GetRecommendedChipset());

    /* Selecting recommended Audio Controller: */
    m_machine.GetAudioAdapter().SetAudioController(type.GetRecommendedAudioController());
    /* And the Audio Codec: */
    m_machine.GetAudioAdapter().SetAudioCodec(type.GetRecommendedAudioCodec());
    /* Enabling audio by default: */
    m_machine.GetAudioAdapter().SetEnabled(true);

    /* Enable the OHCI and EHCI controller by default for new VMs. (new in 2.2): */
    CUSBDeviceFilters usbDeviceFilters = m_machine.GetUSBDeviceFilters();
    bool fOhciEnabled = false;
    if (!usbDeviceFilters.isNull() && type.GetRecommendedUSB3() && m_machine.GetUSBProxyAvailable())
    {
        /* USB 3.0 is only available if the proper ExtPack is installed. */
        CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager();
        if (manager.IsExtPackUsable(GUI_ExtPackName))
        {
            m_machine.AddUSBController("XHCI", KUSBControllerType_XHCI);
            /* xHci includes OHCI */
            fOhciEnabled = true;
        }
    }
    if (   !fOhciEnabled
        && !usbDeviceFilters.isNull() && type.GetRecommendedUSB() && m_machine.GetUSBProxyAvailable())
    {
        m_machine.AddUSBController("OHCI", KUSBControllerType_OHCI);
        fOhciEnabled = true;
        /* USB 2.0 is only available if the proper ExtPack is installed.
         * Note. Configuring EHCI here and providing messages about
         * the missing extpack isn't exactly clean, but it is a
         * necessary evil to patch over legacy compatability issues
         * introduced by the new distribution model. */
        CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager();
        if (manager.IsExtPackUsable(GUI_ExtPackName))
            m_machine.AddUSBController("EHCI", KUSBControllerType_EHCI);
    }

    /* Create a floppy controller if recommended: */
    QString strFloppyName = getNextControllerName(KStorageBus_Floppy);
    if (type.GetRecommendedFloppy())
    {
        m_machine.AddStorageController(strFloppyName, KStorageBus_Floppy);
        CStorageController flpCtr = m_machine.GetStorageControllerByName(strFloppyName);
        flpCtr.SetControllerType(KStorageControllerType_I82078);
    }

    /* Create recommended DVD storage controller: */
    KStorageBus strDVDBus = type.GetRecommendedDVDStorageBus();
    QString strDVDName = getNextControllerName(strDVDBus);
    m_machine.AddStorageController(strDVDName, strDVDBus);

    /* Set recommended DVD storage controller type: */
    CStorageController dvdCtr = m_machine.GetStorageControllerByName(strDVDName);
    KStorageControllerType dvdStorageControllerType = type.GetRecommendedDVDStorageController();
    dvdCtr.SetControllerType(dvdStorageControllerType);

    /* Create recommended HD storage controller if it's not the same as the DVD controller: */
    KStorageBus ctrHDBus = type.GetRecommendedHDStorageBus();
    KStorageControllerType hdStorageControllerType = type.GetRecommendedHDStorageController();
    CStorageController hdCtr;
    QString strHDName;
    if (ctrHDBus != strDVDBus || hdStorageControllerType != dvdStorageControllerType)
    {
        strHDName = getNextControllerName(ctrHDBus);
        m_machine.AddStorageController(strHDName, ctrHDBus);
        hdCtr = m_machine.GetStorageControllerByName(strHDName);
        hdCtr.SetControllerType(hdStorageControllerType);
    }
    else
    {
        /* The HD controller is the same as DVD: */
        hdCtr = dvdCtr;
        strHDName = strDVDName;
    }

    /* Liomit the AHCI port count if it's used because windows has trouble with
       too many ports and other guest (OS X in particular) may take extra long
       to boot: */
    if (hdStorageControllerType == KStorageControllerType_IntelAhci)
        hdCtr.SetPortCount(1 + (dvdStorageControllerType == KStorageControllerType_IntelAhci));
    else if (dvdStorageControllerType == KStorageControllerType_IntelAhci)
        dvdCtr.SetPortCount(1);

    /* Turn on PAE, if recommended: */
    m_machine.SetCPUProperty(KCPUPropertyType_PAE, type.GetRecommendedPAE());

    /* Set the recommended triple fault behavior: */
    m_machine.SetCPUProperty(KCPUPropertyType_TripleFaultReset, type.GetRecommendedTFReset());

    /* Set recommended firmware type: */
    KFirmwareType fwType = type.GetRecommendedFirmware();
    m_machine.SetFirmwareType(fwType);

    /* Set recommended human interface device types: */
    if (type.GetRecommendedUSBHID())
    {
        m_machine.SetKeyboardHIDType(KKeyboardHIDType_USBKeyboard);
        m_machine.SetPointingHIDType(KPointingHIDType_USBMouse);
        if (!fOhciEnabled && !usbDeviceFilters.isNull())
            m_machine.AddUSBController("OHCI", KUSBControllerType_OHCI);
    }

    if (type.GetRecommendedUSBTablet())
    {
        m_machine.SetPointingHIDType(KPointingHIDType_USBTablet);
        if (!fOhciEnabled && !usbDeviceFilters.isNull())
            m_machine.AddUSBController("OHCI", KUSBControllerType_OHCI);
    }

    /* Set HPET flag: */
    m_machine.SetHPETEnabled(type.GetRecommendedHPET());

    /* Set UTC flags: */
    m_machine.SetRTCUseUTC(type.GetRecommendedRTCUseUTC());

    /* Set graphic bits: */
    if (type.GetRecommended2DVideoAcceleration())
        m_machine.SetAccelerate2DVideoEnabled(type.GetRecommended2DVideoAcceleration());

    if (type.GetRecommended3DAcceleration())
        m_machine.SetAccelerate3DEnabled(type.GetRecommended3DAcceleration());

    /* Register the VM prior to attaching hard disks: */
    vbox.RegisterMachine(m_machine);
    if (!vbox.isOk())
    {
        msgCenter().cannotRegisterMachine(vbox, m_machine.GetName(), this);
        return false;
    }

    /* Attach default devices: */
    {
        bool success = false;
        QString strMachineId = m_machine.GetId();
        CSession session = vboxGlobal().openSession(strMachineId);
        if (!session.isNull())
        {
            CMachine machine = session.GetMachine();

            QString strId = field("virtualDiskId").toString();
            /* Boot virtual hard drive: */
            if (!strId.isNull())
            {
                UIMedium vmedium = vboxGlobal().medium(strId);
                CMedium medium = vmedium.medium();              // @todo r=dj can this be cached somewhere?
                machine.AttachDevice(strHDName, 0, 0, KDeviceType_HardDisk, medium);
                if (!machine.isOk())
                    msgCenter().cannotAttachDevice(machine, UIMediumType_HardDisk, field("virtualDiskLocation").toString(),
                                                   StorageSlot(ctrHDBus, 0, 0), this);
            }

            /* Attach empty optical drive: */
            machine.AttachDevice(strDVDName, 1, 0, KDeviceType_DVD, CMedium());
            if (!machine.isOk())
                msgCenter().cannotAttachDevice(machine, UIMediumType_DVD, QString(), StorageSlot(strDVDBus, 1, 0), this);


            /* Attach an empty floppy drive if recommended */
            if (type.GetRecommendedFloppy()) {
                machine.AttachDevice(strFloppyName, 0, 0, KDeviceType_Floppy, CMedium());
                if (!machine.isOk())
                    msgCenter().cannotAttachDevice(machine, UIMediumType_Floppy, QString(),
                                                   StorageSlot(KStorageBus_Floppy, 0, 0), this);
            }

            if (machine.isOk())
            {
                machine.SaveSettings();
                if (machine.isOk())
                    success = true;
                else
                    msgCenter().cannotSaveMachineSettings(machine, this);
            }

            session.UnlockMachine();
        }
        if (!success)
        {
            /* Unregister on failure */
            QVector<CMedium> aMedia = m_machine.Unregister(KCleanupMode_UnregisterOnly);   //  @todo replace with DetachAllReturnHardDisksOnly once a progress dialog is in place below
            if (vbox.isOk())
            {
                CProgress progress = m_machine.DeleteConfig(aMedia);
                progress.WaitForCompletion(-1);         // @todo do this nicely with a progress dialog, this can delete lots of files
            }
            return false;
        }
    }

    /* Ensure we don't try to delete a newly created virtual hard drive on success: */
    if (!field("virtualDisk").value<CMedium>().isNull())
        field("virtualDisk").value<CMedium>().detach();

    return true;
}
bool UIApplianceImportEditorWidget::setFile(const QString& strFile)
{
    bool fResult = false;
    if (!strFile.isEmpty())
    {
        CProgress progress;
        CVirtualBox vbox = vboxGlobal().virtualBox();
        /* Create a appliance object */
        m_pAppliance = new CAppliance(vbox.CreateAppliance());
        fResult = m_pAppliance->isOk();
        if (fResult)
        {
            /* Read the appliance */
            progress = m_pAppliance->Read(strFile);
            fResult = m_pAppliance->isOk();
            if (fResult)
            {
                /* Show some progress, so the user know whats going on */
                msgCenter().showModalProgressDialog(progress, tr("Reading Appliance ..."), "", this);
                if (!progress.isOk() || progress.GetResultCode() != 0)
                    fResult = false;
                else
                {
                    /* Now we have to interpret that stuff */
                    m_pAppliance->Interpret();
                    fResult = m_pAppliance->isOk();
                    if (fResult)
                    {
                        if (m_pModel)
                            delete m_pModel;

                        QVector<CVirtualSystemDescription> vsds = m_pAppliance->GetVirtualSystemDescriptions();

                        m_pModel = new VirtualSystemModel(vsds, this);

                        ImportSortProxyModel *pProxy = new ImportSortProxyModel(this);
                        pProxy->setSourceModel(m_pModel);
                        pProxy->sort(DescriptionSection, Qt::DescendingOrder);

                        VirtualSystemDelegate *pDelegate = new VirtualSystemDelegate(pProxy, this);

                        /* Set our own model */
                        m_pTvSettings->setModel(pProxy);
                        /* Set our own delegate */
                        m_pTvSettings->setItemDelegate(pDelegate);
                        /* For now we hide the original column. This data is displayed as tooltip
                           also. */
                        m_pTvSettings->setColumnHidden(OriginalValueSection, true);
                        m_pTvSettings->expandAll();

                        /* Check for warnings & if there are one display them. */
                        bool fWarningsEnabled = false;
                        QVector<QString> warnings = m_pAppliance->GetWarnings();
                        if (warnings.size() > 0)
                        {
                            foreach (const QString& text, warnings)
                                mWarningTextEdit->append("- " + text);
                            fWarningsEnabled = true;
                        }
                        m_pWarningWidget->setShown(fWarningsEnabled);
                    }
                }
            }
        }
void UIMachineSettingsGeneral::saveFromCacheTo(QVariant &data)
{
    /* Fetch data to machine: */
    UISettingsPageMachine::fetchData(data);

    /* Check if general data was changed: */
    if (m_cache.wasChanged())
    {
        /* Get general data from cache: */
        const UIDataSettingsMachineGeneral &generalData = m_cache.data();

        if (isMachineInValidMode())
        {
            /* 'Advanced' tab data: */
            if (generalData.m_clipboardMode != m_cache.base().m_clipboardMode)
                m_machine.SetClipboardMode(generalData.m_clipboardMode);
            if (generalData.m_dndMode != m_cache.base().m_dndMode)
                m_machine.SetDnDMode(generalData.m_dndMode);

            /* 'Description' tab: */
            if (generalData.m_strDescription != m_cache.base().m_strDescription)
                m_machine.SetDescription(generalData.m_strDescription);
        }

        if (isMachineOffline())
        {
            /* 'Basic' tab data: Must update long mode CPU feature bit when os type changes. */
            if (generalData.m_strGuestOsTypeId != m_cache.base().m_strGuestOsTypeId)
            {
                m_machine.SetOSTypeId(generalData.m_strGuestOsTypeId);
                CVirtualBox vbox = vboxGlobal().virtualBox();
                CGuestOSType newType = vbox.GetGuestOSType(generalData.m_strGuestOsTypeId);
                m_machine.SetCPUProperty(KCPUPropertyType_LongMode, newType.GetIs64Bit());
            }

            /* 'Advanced' tab data: */
            if (generalData.m_strSnapshotsFolder != m_cache.base().m_strSnapshotsFolder)
                m_machine.SetSnapshotFolder(generalData.m_strSnapshotsFolder);

            /* 'Basic' (again) tab data: */
            /* VM name must be last as otherwise its VM rename magic
             * can collide with other settings in the config,
             * especially with the snapshot folder: */
            if (generalData.m_strName != m_cache.base().m_strName)
                m_machine.SetName(generalData.m_strName);

            /* Encryption tab data: */
            if (generalData.m_fEncryptionEnabled != m_cache.base().m_fEncryptionEnabled ||
                generalData.m_fEncryptionCipherChanged != m_cache.base().m_fEncryptionCipherChanged ||
                generalData.m_fEncryptionPasswordChanged != m_cache.base().m_fEncryptionPasswordChanged)
            {
                /* Cipher attribute changed? */
                QString strNewCipher;
                if (generalData.m_fEncryptionCipherChanged)
                {
                    strNewCipher = generalData.m_fEncryptionEnabled ?
                                   m_encryptionCiphers.at(generalData.m_iEncryptionCipherIndex) : QString();
                }
                /* Password attribute changed? */
                QString strNewPassword;
                QString strNewPasswordId;
                if (generalData.m_fEncryptionPasswordChanged)
                {
                    strNewPassword = generalData.m_fEncryptionEnabled ?
                                     generalData.m_strEncryptionPassword : QString();
                    strNewPasswordId = generalData.m_fEncryptionEnabled ?
                                       m_machine.GetName() : QString();
                }

                /* Get the maps of encrypted mediums and their passwords: */
                const EncryptedMediumMap &encryptedMedium = generalData.m_encryptedMediums;
                const EncryptionPasswordMap &encryptionPasswords = generalData.m_encryptionPasswords;
                /* Enumerate attachments: */
                foreach (const CMediumAttachment &attachment, m_machine.GetMediumAttachments())
                {
                    /* Enumerate hard-drives only: */
                    if (attachment.GetType() == KDeviceType_HardDisk)
                    {
                        /* Get corresponding medium: */
                        CMedium medium = attachment.GetMedium();

                        /* Check if old password exists/provided: */
                        QString strOldPasswordId = encryptedMedium.key(medium.GetId());
                        QString strOldPassword = encryptionPasswords.value(strOldPasswordId);

                        /* Update encryption: */
                        CProgress cprogress = medium.ChangeEncryption(strOldPassword,
                                                                      strNewCipher,
                                                                      strNewPassword,
                                                                      strNewPasswordId);
                        if (!medium.isOk())
                        {
                            QMetaObject::invokeMethod(this, "sigOperationProgressError", Qt::BlockingQueuedConnection,
                                                      Q_ARG(QString, UIMessageCenter::formatErrorInfo(medium)));
                            continue;
                        }
                        UIProgress uiprogress(cprogress);
                        connect(&uiprogress, SIGNAL(sigProgressChange(ulong, QString, ulong, ulong)),
                                this, SIGNAL(sigOperationProgressChange(ulong, QString, ulong, ulong)),
                                Qt::QueuedConnection);
                        connect(&uiprogress, SIGNAL(sigProgressError(QString)),
                                this, SIGNAL(sigOperationProgressError(QString)),
                                Qt::BlockingQueuedConnection);
                        uiprogress.run(350);
                    }
                }
            }
        }
    }
Beispiel #22
0
/* Save data from cache to corresponding external object(s),
 * this task COULD be performed in other than GUI thread: */
void UIGlobalSettingsNetwork::saveFromCacheTo(QVariant &data)
{
    /* Ensure settings were changed: */
    if (!m_fChanged)
        return;

    /* Fetch data to properties & settings: */
    UISettingsPageGlobal::fetchData(data);

    /* Prepare useful variables: */
    CVirtualBox vbox = vboxGlobal().virtualBox();
    CHost host = vboxGlobal().host();

    /* Update all the host-only interfaces: */
    for (int iNetworkIndex = 0; iNetworkIndex < m_cache.m_items.size(); ++iNetworkIndex)
    {
        /* Get iterated data: */
        const UIHostNetworkData &data = m_cache.m_items[iNetworkIndex];
        /* Find corresponding interface: */
        CHostNetworkInterface iface = host.FindHostNetworkInterfaceByName(data.m_interface.m_strName);
        if (!iface.isNull())
        {
            /* Host-only interface configuring: */
            if (data.m_interface.m_fDhcpClientEnabled)
            {
                iface.EnableDynamicIPConfig();
            }
            else
            {
                AssertMsg(data.m_interface.m_strInterfaceAddress.isEmpty() ||
                          QHostAddress(data.m_interface.m_strInterfaceAddress).protocol() == QAbstractSocket::IPv4Protocol,
                          ("Interface IPv4 address must be empty or IPv4-valid!\n"));
                AssertMsg(data.m_interface.m_strInterfaceMask.isEmpty() ||
                          QHostAddress(data.m_interface.m_strInterfaceMask).protocol() == QAbstractSocket::IPv4Protocol,
                          ("Interface IPv4 network mask must be empty or IPv4-valid!\n"));
                iface.EnableStaticIPConfig(data.m_interface.m_strInterfaceAddress, data.m_interface.m_strInterfaceMask);
                if (iface.GetIPV6Supported())
                {
                    AssertMsg(data.m_interface.m_strInterfaceAddress6.isEmpty() ||
                              QHostAddress(data.m_interface.m_strInterfaceAddress6).protocol() == QAbstractSocket::IPv6Protocol,
                              ("Interface IPv6 address must be empty or IPv6-valid!\n"));
                    iface.EnableStaticIPConfigV6(data.m_interface.m_strInterfaceAddress6, data.m_interface.m_strInterfaceMaskLength6.toULong());
                }
            }

            /* Find corresponding DHCP server: */
            CDHCPServer dhcp = vbox.FindDHCPServerByNetworkName(iface.GetNetworkName());
            if (!dhcp.isNull())
            {
                /* DHCP server configuring: */
                dhcp.SetEnabled(data.m_dhcpserver.m_fDhcpServerEnabled);
                AssertMsg(QHostAddress(data.m_dhcpserver.m_strDhcpServerAddress).protocol() == QAbstractSocket::IPv4Protocol,
                          ("DHCP server IPv4 address must be IPv4-valid!\n"));
                AssertMsg(QHostAddress(data.m_dhcpserver.m_strDhcpServerMask).protocol() == QAbstractSocket::IPv4Protocol,
                          ("DHCP server IPv4 network mask must be IPv4-valid!\n"));
                AssertMsg(QHostAddress(data.m_dhcpserver.m_strDhcpLowerAddress).protocol() == QAbstractSocket::IPv4Protocol,
                          ("DHCP server IPv4 lower bound must be IPv4-valid!\n"));
                AssertMsg(QHostAddress(data.m_dhcpserver.m_strDhcpUpperAddress).protocol() == QAbstractSocket::IPv4Protocol,
                          ("DHCP server IPv4 upper bound must be IPv4-valid!\n"));
                if (QHostAddress(data.m_dhcpserver.m_strDhcpServerAddress).protocol() == QAbstractSocket::IPv4Protocol &&
                    QHostAddress(data.m_dhcpserver.m_strDhcpServerMask).protocol() == QAbstractSocket::IPv4Protocol &&
                    QHostAddress(data.m_dhcpserver.m_strDhcpLowerAddress).protocol() == QAbstractSocket::IPv4Protocol &&
                    QHostAddress(data.m_dhcpserver.m_strDhcpUpperAddress).protocol() == QAbstractSocket::IPv4Protocol)
                    dhcp.SetConfiguration(data.m_dhcpserver.m_strDhcpServerAddress, data.m_dhcpserver.m_strDhcpServerMask,
                                          data.m_dhcpserver.m_strDhcpLowerAddress, data.m_dhcpserver.m_strDhcpUpperAddress);
            }
        }
    }

    /* Upload properties & settings to data: */
    UISettingsPageGlobal::uploadData(data);
}
Beispiel #23
0
bool UIWizardCloneVM::cloneVM()
{
    /* Get clone name: */
    QString strName = field("cloneName").toString();
    /* Should we reinit mac status? */
    bool fReinitMACs = field("reinitMACs").toBool();
    /* Should we create linked clone? */
    bool fLinked = field("linkedClone").toBool();
    /* Get clone mode: */
    KCloneMode cloneMode = (mode() == UIWizardMode_Basic && page(Page3)) ||
                           (mode() == UIWizardMode_Expert && page(PageExpert)) ?
                           field("cloneMode").value<KCloneMode>() : KCloneMode_MachineState;

    /* Get VBox object: */
    CVirtualBox vbox = vboxGlobal().virtualBox();

    /* Prepare machine for cloning: */
    CMachine srcMachine = m_machine;

    /* If the user like to create a linked clone from the current machine, we
     * have to take a little bit more action. First we create an snapshot, so
     * that new differencing images on the source VM are created. Based on that
     * we could use the new snapshot machine for cloning. */
    if (fLinked && m_snapshot.isNull())
    {
        /* Open session: */
        CSession session = vboxGlobal().openSession(m_machine.GetId());
        if (session.isNull())
            return false;

        /* Prepare console: */
        CConsole console = session.GetConsole();

        /* Take the snapshot: */
        QString strSnapshotName = tr("Linked Base for %1 and %2").arg(m_machine.GetName()).arg(strName);
        CProgress progress = console.TakeSnapshot(strSnapshotName, "");

        if (console.isOk())
        {
            /* Show the "Taking Snapshot" progress dialog: */
            msgCenter().showModalProgressDialog(progress, m_machine.GetName(), ":/progress_snapshot_create_90px.png", this, true);

            if (!progress.isOk() || progress.GetResultCode() != 0)
            {
                msgCenter().cannotTakeSnapshot(progress);
                return false;
            }
        }
        else
        {
            msgCenter().cannotTakeSnapshot(console);
            return false;
        }

        /* Unlock machine finally: */
        session.UnlockMachine();

        /* Get the new snapshot and the snapshot machine. */
        const CSnapshot &newSnapshot = m_machine.FindSnapshot(strSnapshotName);
        if (newSnapshot.isNull())
        {
            msgCenter().cannotFindSnapshotByName(this, m_machine, strSnapshotName);
            return false;
        }
        srcMachine = newSnapshot.GetMachine();
    }

    /* Create a new machine object. */
    const QString &strSettingsFile = vbox.ComposeMachineFilename(strName, QString::null /**< @todo group support */, QString::null, QString::null);
    CMachine cloneMachine = vbox.CreateMachine(strSettingsFile, strName, QVector<QString>(), QString::null, QString::null);
    if (!vbox.isOk())
    {
        msgCenter().cannotCreateMachine(vbox, this);
        return false;
    }

    /* Add the keep all MACs option to the import settings when requested. */
    QVector<KCloneOptions> options;
    if (!fReinitMACs)
        options.append(KCloneOptions_KeepAllMACs);
    /* Linked clones requested? */
    if (fLinked)
        options.append(KCloneOptions_Link);

    /* Start cloning. */
    CProgress progress = srcMachine.CloneTo(cloneMachine, cloneMode, options);
    if (!srcMachine.isOk())
    {
        msgCenter().cannotCreateClone(srcMachine, this);
        return false;
    }

    /* Wait until done. */
    msgCenter().showModalProgressDialog(progress, windowTitle(), ":/progress_clone_90px.png", this, true);
    if (progress.GetCanceled())
        return false;
    if (!progress.isOk() || progress.GetResultCode() != 0)
    {
        msgCenter().cannotCreateClone(srcMachine, progress, this);
        return false;
    }

    /* Finally register the clone machine. */
    vbox.RegisterMachine(cloneMachine);
    if (!vbox.isOk())
    {
        msgCenter().cannotRegisterMachine(vbox, cloneMachine, this);
        return false;
    }

    return true;
}
Beispiel #24
0
bool UINewVMWzdPage5::constructMachine()
{
    CVirtualBox vbox = vboxGlobal().virtualBox();

    /* OS type */
    CGuestOSType type = field("type").value<CGuestOSType>();
    AssertMsg(!type.isNull(), ("GuestOSType must return non-null type"));
    QString typeId = type.GetId();

    /* Create a machine with the default settings file location */
    if (m_Machine.isNull())
    {
        m_Machine = vbox.CreateMachine(QString::null,       // auto-compose filename
                                       field("name").toString(),
                                       typeId,
                                       QString::null,       // machine ID
                                       false);              // forceOverwrite
        if (!vbox.isOk())
        {
            msgCenter().cannotCreateMachine(vbox, this);
            return false;
        }

        /* The FirstRun wizard is to be shown only when we don't attach any hard disk or attach a new (empty) one.
         * Selecting an existing hard disk will cancel the wizard. */
        if (field("hardDiskId").toString().isNull() || !field("hardDisk").value<CMedium>().isNull())
            m_Machine.SetExtraData(VBoxDefs::GUI_FirstRun, "yes");
    }

    /* RAM size */
    m_Machine.SetMemorySize(field("ram").toInt());

    /* VRAM size - select maximum between recommended and minimum for fullscreen */
    m_Machine.SetVRAMSize (qMax (type.GetRecommendedVRAM(),
                                (ULONG) (VBoxGlobal::requiredVideoMemory(typeId) / _1M)));

    /* Selecting recommended chipset type */
    m_Machine.SetChipsetType(type.GetRecommendedChipset());

    /* Selecting recommended Audio Controller */
    m_Machine.GetAudioAdapter().SetAudioController(type.GetRecommendedAudioController());
    /* Enabling audio by default */
    m_Machine.GetAudioAdapter().SetEnabled(true);

    /* Enable the OHCI and EHCI controller by default for new VMs. (new in 2.2) */
    CUSBController usbController = m_Machine.GetUSBController();
    if (   !usbController.isNull()
        && usbController.GetProxyAvailable())
    {
        usbController.SetEnabled(true);

        /*
         * USB 2.0 is only available if the proper ExtPack is installed.
         *
         * Note. Configuring EHCI here and providing messages about
         * the missing extpack isn't exactly clean, but it is a
         * necessary evil to patch over legacy compatability issues
         * introduced by the new distribution model.
         */
        CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager();
        if (manager.IsExtPackUsable(UI_ExtPackName))
            usbController.SetEnabledEhci(true);
    }

    /* Create recommended DVD storage controller */
    KStorageBus ctrDvdBus = type.GetRecommendedDvdStorageBus();
    QString ctrDvdName = getNextControllerName(ctrDvdBus);
    m_Machine.AddStorageController(ctrDvdName, ctrDvdBus);

    /* Set recommended DVD storage controller type */
    CStorageController dvdCtr = m_Machine.GetStorageControllerByName(ctrDvdName);
    KStorageControllerType dvdStorageControllerType = type.GetRecommendedDvdStorageController();
    dvdCtr.SetControllerType(dvdStorageControllerType);

    /* Create recommended HD storage controller if it's not the same as the DVD controller */
    KStorageBus ctrHdBus = type.GetRecommendedHdStorageBus();
    KStorageControllerType hdStorageControllerType = type.GetRecommendedHdStorageController();
    CStorageController hdCtr;
    QString ctrHdName;
    if (ctrHdBus != ctrDvdBus || hdStorageControllerType != dvdStorageControllerType)
    {
        ctrHdName = getNextControllerName(ctrHdBus);
        m_Machine.AddStorageController(ctrHdName, ctrHdBus);
        hdCtr = m_Machine.GetStorageControllerByName(ctrHdName);
        hdCtr.SetControllerType(hdStorageControllerType);

        /* Set the port count to 1 if SATA is used. */
        if (hdStorageControllerType == KStorageControllerType_IntelAhci)
            hdCtr.SetPortCount(1);
    }
    else
    {
        /* The HD controller is the same as DVD */
        hdCtr = dvdCtr;
        ctrHdName = ctrDvdName;
    }

    /* Turn on PAE, if recommended */
    m_Machine.SetCPUProperty(KCPUPropertyType_PAE, type.GetRecommendedPae());

    /* Set recommended firmware type */
    KFirmwareType fwType = type.GetRecommendedFirmware();
    m_Machine.SetFirmwareType(fwType);

    /* Set recommended human interface device types */
    if (type.GetRecommendedUsbHid())
    {
        m_Machine.SetKeyboardHidType(KKeyboardHidType_USBKeyboard);
        m_Machine.SetPointingHidType(KPointingHidType_USBMouse);
        if (!usbController.isNull())
            usbController.SetEnabled(true);
    }

    if (type.GetRecommendedUsbTablet())
    {
        m_Machine.SetPointingHidType(KPointingHidType_USBTablet);
        if (!usbController.isNull())
            usbController.SetEnabled(true);
    }

    /* Set HPET flag */
    m_Machine.SetHpetEnabled(type.GetRecommendedHpet());

    /* Set UTC flags */
    m_Machine.SetRTCUseUTC(type.GetRecommendedRtcUseUtc());

    /* Register the VM prior to attaching hard disks */
    vbox.RegisterMachine(m_Machine);
    if (!vbox.isOk())
    {
        msgCenter().cannotCreateMachine(vbox, m_Machine, this);
        return false;
    }

    /* Attach default devices */
    {
        bool success = false;
        QString machineId = m_Machine.GetId();
        CSession session = vboxGlobal().openSession(machineId);
        if (!session.isNull())
        {
            CMachine m = session.GetMachine();

            QString strId = field("hardDiskId").toString();
            /* Boot hard disk */
            if (!strId.isNull())
            {
                VBoxMedium vmedium = vboxGlobal().findMedium(strId);
                CMedium medium = vmedium.medium();              // @todo r=dj can this be cached somewhere?
                m.AttachDevice(ctrHdName, 0, 0, KDeviceType_HardDisk, medium);
                if (!m.isOk())
                    msgCenter().cannotAttachDevice(m, VBoxDefs::MediumType_HardDisk, field("hardDiskLocation").toString(),
                                                     StorageSlot(ctrHdBus, 0, 0), this);
            }

            /* Attach empty CD/DVD ROM Device */
            m.AttachDevice(ctrDvdName, 1, 0, KDeviceType_DVD, CMedium());
            if (!m.isOk())
                msgCenter().cannotAttachDevice(m, VBoxDefs::MediumType_DVD, QString(), StorageSlot(ctrDvdBus, 1, 0), this);

            if (m.isOk())
            {
                m.SaveSettings();
                if (m.isOk())
                    success = true;
                else
                    msgCenter().cannotSaveMachineSettings(m, this);
            }

            session.UnlockMachine();
        }
        if (!success)
        {
            /* Unregister on failure */
            QVector<CMedium> aMedia = m_Machine.Unregister(KCleanupMode_UnregisterOnly);   //  @todo replace with DetachAllReturnHardDisksOnly once a progress dialog is in place below
            if (vbox.isOk())
            {
                CProgress progress = m_Machine.Delete(aMedia);
                progress.WaitForCompletion(-1);         // @todo do this nicely with a progress dialog, this can delete lots of files
            }
            return false;
        }
    }

    /* Ensure we don't try to delete a newly created hard disk on success */
    if (!field("hardDisk").value<CMedium>().isNull())
        field("hardDisk").value<CMedium>().detach();

    return true;
}
void UIHostNetworkManagerWidget::sltApplyHostNetworkDetailsChanges()
{
    /* Get network item: */
    UIItemHostNetwork *pItem = static_cast<UIItemHostNetwork*>(m_pTreeWidget->currentItem());
    AssertMsgReturnVoid(pItem, ("Current item must not be null!\n"));

    /* Get item data: */
    UIDataHostNetwork oldData = *pItem;
    UIDataHostNetwork newData = m_pDetailsWidget->data();

    /* Get host for further activities: */
    CHost comHost = vboxGlobal().host();

    /* Find corresponding interface: */
    CHostNetworkInterface comInterface = comHost.FindHostNetworkInterfaceByName(oldData.m_interface.m_strName);

    /* Show error message if necessary: */
    if (!comHost.isOk() || comInterface.isNull())
        msgCenter().cannotFindHostNetworkInterface(comHost, oldData.m_interface.m_strName, this);
    else
    {
        /* Save automatic interface configuration: */
        if (newData.m_interface.m_fDHCPEnabled)
        {
            if (   comInterface.isOk()
                && !oldData.m_interface.m_fDHCPEnabled)
                comInterface.EnableDynamicIPConfig();
        }
        /* Save manual interface configuration: */
        else
        {
            /* Save IPv4 interface configuration: */
            if (   comInterface.isOk()
                && (   oldData.m_interface.m_fDHCPEnabled
                    || newData.m_interface.m_strAddress != oldData.m_interface.m_strAddress
                    || newData.m_interface.m_strMask != oldData.m_interface.m_strMask))
                comInterface.EnableStaticIPConfig(newData.m_interface.m_strAddress, newData.m_interface.m_strMask);
            /* Save IPv6 interface configuration: */
            if (   comInterface.isOk()
                && newData.m_interface.m_fSupportedIPv6
                && (   oldData.m_interface.m_fDHCPEnabled
                    || newData.m_interface.m_strAddress6 != oldData.m_interface.m_strAddress6
                    || newData.m_interface.m_strPrefixLength6 != oldData.m_interface.m_strPrefixLength6))
                comInterface.EnableStaticIPConfigV6(newData.m_interface.m_strAddress6, newData.m_interface.m_strPrefixLength6.toULong());
        }

        /* Show error message if necessary: */
        if (!comInterface.isOk())
            msgCenter().cannotSaveHostNetworkInterfaceParameter(comInterface, this);
        else
        {
            /* Get network name for further activities: */
            const QString strNetworkName = comInterface.GetNetworkName();

            /* Show error message if necessary: */
            if (!comInterface.isOk())
                msgCenter().cannotAcquireHostNetworkInterfaceParameter(comInterface, this);
            else
            {
                /* Get VBox for further activities: */
                CVirtualBox comVBox = vboxGlobal().virtualBox();

                /* Find corresponding DHCP server (create if necessary): */
                CDHCPServer comServer = comVBox.FindDHCPServerByNetworkName(strNetworkName);
                if (!comVBox.isOk() || comServer.isNull())
                    comServer = comVBox.CreateDHCPServer(strNetworkName);

                /* Show error message if necessary: */
                if (!comVBox.isOk() || comServer.isNull())
                    msgCenter().cannotCreateDHCPServer(comVBox, strNetworkName, this);
                else
                {
                    /* Save whether DHCP server is enabled: */
                    if (   comServer.isOk()
                        && newData.m_dhcpserver.m_fEnabled != oldData.m_dhcpserver.m_fEnabled)
                        comServer.SetEnabled(newData.m_dhcpserver.m_fEnabled);
                    /* Save DHCP server configuration: */
                    if (   comServer.isOk()
                        && newData.m_dhcpserver.m_fEnabled
                        && (   newData.m_dhcpserver.m_strAddress != oldData.m_dhcpserver.m_strAddress
                            || newData.m_dhcpserver.m_strMask != oldData.m_dhcpserver.m_strMask
                            || newData.m_dhcpserver.m_strLowerAddress != oldData.m_dhcpserver.m_strLowerAddress
                            || newData.m_dhcpserver.m_strUpperAddress != oldData.m_dhcpserver.m_strUpperAddress))
                        comServer.SetConfiguration(newData.m_dhcpserver.m_strAddress, newData.m_dhcpserver.m_strMask,
                                                   newData.m_dhcpserver.m_strLowerAddress, newData.m_dhcpserver.m_strUpperAddress);

                    /* Show error message if necessary: */
                    if (!comServer.isOk())
                        msgCenter().cannotSaveDHCPServerParameter(comServer, this);
                }
            }
        }

        /* Find corresponding interface again (if necessary): */
        if (!comInterface.isOk())
        {
            comInterface = comHost.FindHostNetworkInterfaceByName(oldData.m_interface.m_strName);

            /* Show error message if necessary: */
            if (!comHost.isOk() || comInterface.isNull())
                msgCenter().cannotFindHostNetworkInterface(comHost, oldData.m_interface.m_strName, this);
        }

        /* If interface is Ok now: */
        if (comInterface.isNotNull() && comInterface.isOk())
        {
            /* Update interface in the tree: */
            UIDataHostNetwork data;
            loadHostNetwork(comInterface, data);
            updateItemForNetworkHost(data, true, pItem);

            /* Make sure current item fetched: */
            sltHandleCurrentItemChange();

            /* Adjust tree-widget: */
            sltAdjustTreeWidget();
        }
    }
}
/**
 * Refreshes the precomposed strings containing such media parameters as
 * location, size by querying the respective data from the associated
 * media object.
 *
 * Note that some string such as #size() are meaningless if the media state is
 * KMediumState_NotCreated (i.e. the medium has not yet been checked for
 * accessibility).
 */
void UIMedium::refresh()
{
    /* Detect basic parameters */
    mId = mMedium.isNull() ? QUuid().toString().remove ('{').remove ('}') : mMedium.GetId();

    mIsHostDrive = mMedium.isNull() ? false : mMedium.GetHostDrive();

    if (mMedium.isNull())
        mName = VBoxGlobal::tr ("Empty", "medium");
    else if (!mIsHostDrive)
        mName = mMedium.GetName();
    else if (mMedium.GetDescription().isEmpty())
        mName = VBoxGlobal::tr ("Host Drive '%1'", "medium").arg (QDir::toNativeSeparators (mMedium.GetLocation()));
    else
        mName = VBoxGlobal::tr ("Host Drive %1 (%2)", "medium").arg (mMedium.GetDescription(), mMedium.GetName());

    mLocation = mMedium.isNull() || mIsHostDrive ? QString ("--") :
                QDir::toNativeSeparators (mMedium.GetLocation());

    if (mType == UIMediumType_HardDisk)
    {
        mHardDiskFormat = mMedium.GetFormat();
        mHardDiskType = vboxGlobal().mediumTypeString (mMedium);
        mStorageDetails = gpConverter->toString((KMediumVariant)mMedium.GetVariant());
        mIsReadOnly = mMedium.GetReadOnly();

        /* Adjust the parent if its possible */
        CMedium parentMedium = mMedium.GetParent();
        Assert (!parentMedium.isNull() || mParent == NULL);

        if (!parentMedium.isNull() && (mParent == NULL || mParent->mMedium != parentMedium))
        {
            /* Search for the parent (might be there) */
            const VBoxMediaList &list = vboxGlobal().currentMediaList();
            for (VBoxMediaList::const_iterator it = list.begin(); it != list.end(); ++ it)
            {
                if ((*it).mType != UIMediumType_HardDisk)
                    break;

                if ((*it).mMedium == parentMedium)
                {
                    mParent = unconst (&*it);
                    break;
                }
            }
        }
    }
    else
    {
        mHardDiskFormat = QString::null;
        mHardDiskType = QString::null;
        mIsReadOnly = false;
    }

    /* Detect sizes */
    if (mState != KMediumState_Inaccessible && mState != KMediumState_NotCreated && !mIsHostDrive)
    {
        mSize = vboxGlobal().formatSize (mMedium.GetSize());
        if (mType == UIMediumType_HardDisk)
            mLogicalSize = vboxGlobal().formatSize(mMedium.GetLogicalSize());
        else
            mLogicalSize = mSize;
    }
    else
    {
        mSize = mLogicalSize = QString ("--");
    }

    /* Detect usage */
    mUsage = QString::null;
    if (!mMedium.isNull())
    {
        mCurStateMachineIds.clear();
        QVector <QString> machineIds = mMedium.GetMachineIds();
        if (machineIds.size() > 0)
        {
            QString sUsage;

            CVirtualBox vbox = vboxGlobal().virtualBox();

            for (QVector <QString>::ConstIterator it = machineIds.begin(); it != machineIds.end(); ++ it)
            {
                CMachine machine = vbox.FindMachine(*it);

                /* UIMedium object can wrap newly created CMedium object which belongs to
                 * not yet registered machine, like while creating VM clone.
                 * We can skip such a machines in usage string.
                 * CVirtualBox::FindMachine() will return null machine for such case. */
                if (machine.isNull())
                    continue;

                QString sName = machine.GetName();
                QString sSnapshots;

                QVector <QString> snapIds = mMedium.GetSnapshotIds (*it);
                for (QVector <QString>::ConstIterator jt = snapIds.begin(); jt != snapIds.end(); ++ jt)
                {
                    if (*jt == *it)
                    {
                        /* The medium is attached to the machine in the current
                         * state, we don't distinguish this for now by always
                         * giving the VM name in front of snapshot names. */
                        mCurStateMachineIds.push_back (*jt);
                        continue;
                    }

                    CSnapshot snapshot = machine.FindSnapshot(*jt);
                    if (!snapshot.isNull())           // can be NULL while takeSnaphot is in progress
                    {
                        if (!sSnapshots.isNull())
                            sSnapshots += ", ";
                        sSnapshots += snapshot.GetName();
                    }
                }

                if (!sUsage.isNull())
                    sUsage += ", ";

                sUsage += sName;

                if (!sSnapshots.isNull())
                {
                    sUsage += QString (" (%2)").arg (sSnapshots);
                    mIsUsedInSnapshots = true;
                }
                else
                    mIsUsedInSnapshots = false;
            }

            if (!sUsage.isEmpty())
                mUsage = sUsage;
        }
    }

    /* Compose the tooltip */
    if (!mMedium.isNull())
    {
        mToolTip = mRow.arg (QString ("<p style=white-space:pre><b>%1</b></p>").arg (mIsHostDrive ? mName : mLocation));

        if (mType == UIMediumType_HardDisk)
        {
            mToolTip += mRow.arg (VBoxGlobal::tr ("<p style=white-space:pre>Type (Format):  %1 (%2)</p>", "medium")
                                                  .arg (mHardDiskType).arg (mHardDiskFormat));
        }

        mToolTip += mRow.arg (VBoxGlobal::tr ("<p>Attached to:  %1</p>", "image")
                                              .arg (mUsage.isNull() ? VBoxGlobal::tr ("<i>Not Attached</i>", "image") : mUsage));

        switch (mState)
        {
            case KMediumState_NotCreated:
            {
                mToolTip += mRow.arg (VBoxGlobal::tr ("<i>Checking accessibility...</i>", "medium"));
                break;
            }
            case KMediumState_Inaccessible:
            {
                if (mResult.isOk())
                {
                    /* Not Accessible */
                    mToolTip += mRow.arg ("<hr>") + mRow.arg (VBoxGlobal::highlight (mLastAccessError, true /* aToolTip */));
                }
                else
                {
                    /* Accessibility check (eg GetState()) itself failed */
                    mToolTip += mRow.arg ("<hr>") + mRow.arg (VBoxGlobal::tr ("Failed to check media accessibility.", "medium")) +
                                mRow.arg (UIMessageCenter::formatErrorInfo (mResult) + ".");
                }
                break;
            }
            default:
                break;
        }
    }

    /* Reset mNoDiffs */
    mNoDiffs.isSet = false;
}
Beispiel #27
0
void UIVMPreviewWindow::sltRecreatePreview()
{
    /* Only do this if we are visible: */
    if (!isVisible())
        return;

    /* Remove preview if any: */
    if (m_pPreviewImg)
    {
        delete m_pPreviewImg;
        m_pPreviewImg = 0;
    }

    /* We are not creating preview for inaccessible VMs: */
    if (m_machineState == KMachineState_Null)
        return;

    if (!m_machine.isNull() && m_vRect.width() > 0 && m_vRect.height() > 0)
    {
        QImage image(size(), QImage::Format_ARGB32);
        image.fill(Qt::transparent);
        QPainter painter(&image);
        bool fDone = false;

        /* Preview enabled? */
        if (m_pUpdateTimer->interval() > 0)
        {
            /* Use the image which may be included in the save state. */
            if (   m_machineState == KMachineState_Saved
                || m_machineState == KMachineState_Restoring)
            {
                ULONG width = 0, height = 0;
                QVector<BYTE> screenData = m_machine.ReadSavedScreenshotPNGToArray(0, width, height);
                if (screenData.size() != 0)
                {
                    QImage shot = QImage::fromData(screenData.data(), screenData.size(), "PNG").scaled(m_vRect.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                    dimImage(shot);
                    painter.drawImage(m_vRect.x(), m_vRect.y(), shot);
                    fDone = true;
                }
            }
            /* Use the current VM output. */
            else if (   m_machineState == KMachineState_Running
//                      || m_machineState == KMachineState_Saving /* Not sure if this is valid */
                     || m_machineState == KMachineState_Paused)
            {
                if (m_session.GetState() == KSessionState_Locked)
                {
                    CVirtualBox vbox = vboxGlobal().virtualBox();
                    if (vbox.isOk())
                    {
                        const CConsole& console = m_session.GetConsole();
                        if (!console.isNull())
                        {
                            CDisplay display = console.GetDisplay();
                            /* Todo: correct aspect radio */
//                            ULONG w, h, bpp;
//                            display.GetScreenResolution(0, w, h, bpp);
//                            QImage shot = QImage(w, h, QImage::Format_RGB32);
//                            shot.fill(Qt::black);
//                            display.TakeScreenShot(0, shot.bits(), shot.width(), shot.height());
                            QVector<BYTE> screenData = display.TakeScreenShotToArray(0, m_vRect.width(), m_vRect.height());
                            if (   display.isOk()
                                && screenData.size() != 0)
                            {
                                /* Unfortunately we have to reorder the pixel
                                 * data, cause the VBox API returns RGBA data,
                                 * which is not a format QImage understand.
                                 * Todo: check for 32bit alignment, for both
                                 * the data and the scanlines. Maybe we need to
                                 * copy the data in any case. */
                                uint32_t *d = (uint32_t*)screenData.data();
                                for (int i = 0; i < screenData.size() / 4; ++i)
                                {
                                    uint32_t e = d[i];
                                    d[i] = RT_MAKE_U32_FROM_U8(RT_BYTE3(e), RT_BYTE2(e), RT_BYTE1(e), RT_BYTE4(e));
                                }

                                QImage shot = QImage((uchar*)d, m_vRect.width(), m_vRect.height(), QImage::Format_RGB32);

                                if (m_machineState == KMachineState_Paused)
                                    dimImage(shot);
                                painter.drawImage(m_vRect.x(), m_vRect.y(), shot);
                                fDone = true;
                            }
                        }
                    }
                }
            }
        }
        if (fDone)
            m_pPreviewImg = new QImage(image);
    }
    update();
}
void UIHostNetworkManagerWidget::sltHandleItemChange(QTreeWidgetItem *pItem)
{
    /* Get network item: */
    UIItemHostNetwork *pChangedItem = static_cast<UIItemHostNetwork*>(pItem);
    AssertMsgReturnVoid(pChangedItem, ("Changed item must not be null!\n"));

    /* Get item data: */
    UIDataHostNetwork oldData = *pChangedItem;

    /* Make sure dhcp server status changed: */
    if (   (   oldData.m_dhcpserver.m_fEnabled
            && pChangedItem->checkState(Column_DHCP) == Qt::Checked)
        || (   !oldData.m_dhcpserver.m_fEnabled
            && pChangedItem->checkState(Column_DHCP) == Qt::Unchecked))
        return;

    /* Get host for further activities: */
    CHost comHost = vboxGlobal().host();

    /* Find corresponding interface: */
    CHostNetworkInterface comInterface = comHost.FindHostNetworkInterfaceByName(oldData.m_interface.m_strName);

    /* Show error message if necessary: */
    if (!comHost.isOk() || comInterface.isNull())
        msgCenter().cannotFindHostNetworkInterface(comHost, oldData.m_interface.m_strName, this);
    else
    {
        /* Get network name for further activities: */
        const QString strNetworkName = comInterface.GetNetworkName();

        /* Show error message if necessary: */
        if (!comInterface.isOk())
            msgCenter().cannotAcquireHostNetworkInterfaceParameter(comInterface, this);
        else
        {
            /* Get VBox for further activities: */
            CVirtualBox comVBox = vboxGlobal().virtualBox();

            /* Find corresponding DHCP server (create if necessary): */
            CDHCPServer comServer = comVBox.FindDHCPServerByNetworkName(strNetworkName);
            if (!comVBox.isOk() || comServer.isNull())
                comServer = comVBox.CreateDHCPServer(strNetworkName);

            /* Show error message if necessary: */
            if (!comVBox.isOk() || comServer.isNull())
                msgCenter().cannotCreateDHCPServer(comVBox, strNetworkName, this);
            else
            {
                /* Save whether DHCP server is enabled: */
                if (comServer.isOk())
                    comServer.SetEnabled(!oldData.m_dhcpserver.m_fEnabled);
                /* Save default DHCP server configuration if current is invalid: */
                if (   comServer.isOk()
                    && !oldData.m_dhcpserver.m_fEnabled
                    && (   oldData.m_dhcpserver.m_strAddress == "0.0.0.0"
                        || oldData.m_dhcpserver.m_strMask == "0.0.0.0"
                        || oldData.m_dhcpserver.m_strLowerAddress == "0.0.0.0"
                        || oldData.m_dhcpserver.m_strUpperAddress == "0.0.0.0"))
                {
                    const QStringList &proposal = makeDhcpServerProposal(oldData.m_interface.m_strAddress,
                                                                         oldData.m_interface.m_strMask);
                    comServer.SetConfiguration(proposal.at(0), proposal.at(1), proposal.at(2), proposal.at(3));
                }

                /* Show error message if necessary: */
                if (!comServer.isOk())
                    msgCenter().cannotSaveDHCPServerParameter(comServer, this);
                {
                    /* Update interface in the tree: */
                    UIDataHostNetwork data;
                    loadHostNetwork(comInterface, data);
                    updateItemForNetworkHost(data, true, pChangedItem);

                    /* Make sure current item fetched: */
                    sltHandleCurrentItemChange();

                    /* Adjust tree-widget: */
                    sltAdjustTreeWidget();
                }
            }
        }
    }
}
bool UICloneVMWizard::createClone(const QString &strName, KCloneMode mode, bool fReinitMACs, bool fLinked /* = false */)
{
    CVirtualBox vbox = vboxGlobal().virtualBox();
    const QString &strSettingsFile = vbox.ComposeMachineFilename(strName, QString::null);

    CMachine srcMachine = m_machine;
    /* If the user like to create a linked clone from the current machine, we
     * have to take a little bit more action. First we create an snapshot, so
     * that new differencing images on the source VM are created. Based on that
     * we could use the new snapshot machine for cloning. */
    if (   fLinked
        && m_snapshot.isNull())
    {
        const QString &strId = m_machine.GetId();
        CSession session = vboxGlobal().openSession(strId);
        if (session.isNull())
            return false;
        CConsole console = session.GetConsole();

        /* Take the snapshot */
        QString strSnapshotName = tr("Linked Base for %1 and %2").arg(m_machine.GetName()).arg(strName);
        CProgress progress = console.TakeSnapshot(strSnapshotName, "");

        if (console.isOk())
        {
            /* Show the "Taking Snapshot" progress dialog */
            msgCenter().showModalProgressDialog(progress, m_machine.GetName(), ":/progress_snapshot_create_90px.png", this, true);

            if (!progress.isOk() || progress.GetResultCode() != 0)
            {
                msgCenter().cannotTakeSnapshot(progress);
                return false;
            }
        }
        else
        {
            msgCenter().cannotTakeSnapshot(console);
            return false;
        }

        /* Unlock machine finally: */
        session.UnlockMachine();

        /* Get the new snapshot and the snapshot machine. */
        const CSnapshot &newSnapshot = m_machine.FindSnapshot(strSnapshotName);
        if (newSnapshot.isNull())
        {
            msgCenter().cannotFindSnapshotByName(this, m_machine, strSnapshotName);
            return false;
        }
        srcMachine = newSnapshot.GetMachine();
    }

    /* Create a new machine object. */
    CMachine cloneMachine = vbox.CreateMachine(strSettingsFile, strName, QString::null, QString::null, false);
    if (!vbox.isOk())
    {
        msgCenter().cannotCreateMachine(vbox, this);
        return false;
    }

    /* Add the keep all MACs option to the import settings when requested. */
    QVector<KCloneOptions> options;
    if (!fReinitMACs)
        options.append(KCloneOptions_KeepAllMACs);
    /* Linked clones requested? */
    if (fLinked)
        options.append(KCloneOptions_Link);

    /* Start cloning. */
    CProgress progress = srcMachine.CloneTo(cloneMachine, mode, options);
    if (!srcMachine.isOk())
    {
        msgCenter().cannotCreateClone(srcMachine, this);
        return false;
    }

    /* Wait until done. */
    msgCenter().showModalProgressDialog(progress, windowTitle(), ":/progress_clone_90px.png", this, true);
    if (progress.GetCanceled())
        return false;
    if (!progress.isOk() || progress.GetResultCode() != 0)
    {
        msgCenter().cannotCreateClone(srcMachine, progress, this);
        return false;
    }

    /* Finally register the clone machine. */
    vbox.RegisterMachine(cloneMachine);
    if (!vbox.isOk())
    {
        msgCenter().cannotRegisterMachine(vbox, cloneMachine, this);
        return false;
    }

    return true;
}