Ejemplo n.º 1
0
bool UIWizardExportApp::exportVMs(CAppliance &appliance)
{
    /* Write the appliance: */
    const QString strVersion = field("OVF09Selected").toBool() ? "ovf-0.9" : "ovf-1.0";
    CProgress progress = appliance.Write(strVersion, field("manifestSelected").toBool() /* fManifest */, uri());
    bool fResult = appliance.isOk();
    if (fResult)
    {
        /* Show some progress, so the user know whats going on: */
        msgCenter().showModalProgressDialog(progress, QApplication::translate("UIWizardExportApp", "Exporting Appliance ..."),
                                            ":/progress_export_90px.png", this, true);
        if (progress.GetCanceled())
            return false;
        if (!progress.isOk() || progress.GetResultCode() != 0)
        {
            msgCenter().cannotExportAppliance(progress, &appliance, this);
            return false;
        }
        else
            return true;
    }
    if (!fResult)
        msgCenter().cannotExportAppliance(&appliance, this);
    return false;
}
Ejemplo n.º 2
0
/* 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);
}
void UIWizardNewVMPage3::ensureNewVirtualDiskDeleted()
{
    /* Make sure virtual-disk exists: */
    if (m_virtualDisk.isNull())
        return;

    /* Remember virtual-disk ID: */
    QString strId = m_virtualDisk.GetId();

    /* 1st step: start delete-storage progress: */
    CProgress progress = m_virtualDisk.DeleteStorage();
    /* Get initial state: */
    bool fSuccess = m_virtualDisk.isOk();

    /* 2nd step: show delete-storage progress: */
    if (fSuccess)
    {
        msgCenter().showModalProgressDialog(progress, thisImp()->windowTitle(), ":/progress_media_delete_90px.png", thisImp(), true);
        fSuccess = progress.isOk() && progress.GetResultCode() == S_OK;
    }

    /* 3rd step: notify GUI about virtual-disk was deleted or show error if any: */
    if (fSuccess)
        vboxGlobal().removeMedium(UIMediumType_HardDisk, strId);
    else
        msgCenter().cannotDeleteHardDiskStorage(thisImp(), m_virtualDisk, progress);

    /* Detach virtual-disk finally: */
    m_virtualDisk.detach();
}
Ejemplo n.º 4
0
void UIWizardNewVMPage3::ensureNewVirtualDiskDeleted()
{
    /* Make sure virtual-disk valid: */
    if (m_virtualDisk.isNull())
        return;

    /* Remember virtual-disk attributes: */
    QString strMediumID = m_virtualDisk.GetId();
    QString strLocation = m_virtualDisk.GetLocation();
    /* Prepare delete storage progress: */
    CProgress progress = m_virtualDisk.DeleteStorage();
    if (m_virtualDisk.isOk())
    {
        /* Show delete storage progress: */
        msgCenter().showModalProgressDialog(progress, thisImp()->windowTitle(), ":/progress_media_delete_90px.png", thisImp());
        if (!progress.isOk() || progress.GetResultCode() != 0)
            msgCenter().cannotDeleteHardDiskStorage(progress, strLocation, thisImp());
    }
    else
        msgCenter().cannotDeleteHardDiskStorage(m_virtualDisk, strLocation, thisImp());

    /* Inform VBoxGlobal about it: */
    vboxGlobal().deleteMedium(strMediumID);

    /* Detach virtual-disk anyway: */
    m_virtualDisk.detach();
}
Ejemplo n.º 5
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;
}
Ejemplo n.º 6
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;
}
/* Package remove procedure: */
void UIGlobalSettingsExtension::sltRemovePackage()
{
    /* Get current item: */
    UIExtensionPackageItem *pItem = m_pPackagesTree &&
                                    m_pPackagesTree->currentItem() &&
                                    m_pPackagesTree->currentItem()->type() == UIExtensionPackageItem::UIItemType ?
                                    static_cast<UIExtensionPackageItem*>(m_pPackagesTree->currentItem()) : 0;

    /* Uninstall chosen package: */
    if (pItem)
    {
        /* Get name of current package: */
        QString strSelectedPackageName = pItem->name();
        /* Ask the user about package removing: */
        if (msgCenter().confirmRemovingPackage(strSelectedPackageName, this))
        {
            /*
             * Uninstall the package.
             */
            CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager();
            /** @todo Refuse this if any VMs are running. */
            QString displayInfo;
#ifdef RT_OS_WINDOWS
            displayInfo.sprintf("hwnd=%#llx", (uint64_t)(uintptr_t)this->winId());
#endif
            CProgress progress = manager.Uninstall(strSelectedPackageName, false /* forced removal? */, displayInfo);
            if (manager.isOk())
            {
                bool fOk = true;
                if (!progress.isNull())
                {
                    msgCenter().showModalProgressDialog(progress, tr("Extensions"));
                    fOk = progress.isOk() && progress.GetResultCode() == 0;
                }
                if (fOk)
                {
                    /* Remove selected package from cache: */
                    for (int i = 0; i < m_cache.m_items.size(); ++i)
                    {
                        if (!strSelectedPackageName.compare(m_cache.m_items[i].m_strName, Qt::CaseInsensitive))
                        {
                            m_cache.m_items.removeAt(i);
                            break;
                        }
                    }

                    /* Remove selected package from tree: */
                    delete pItem;
                }
                else
                    msgCenter().cannotUninstallExtPack(strSelectedPackageName, manager, progress, this);
            }
            else
                msgCenter().cannotUninstallExtPack(strSelectedPackageName, manager, progress, this);
        }
    }
}
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();
        }
    }
}
/* static */
bool UIMachine::startMachine(const QString &strID)
{
    /* Some restrictions: */
    AssertMsgReturn(vboxGlobal().isValid(), ("VBoxGlobal is invalid.."), false);
    AssertMsgReturn(!vboxGlobal().virtualMachine(), ("Machine already started.."), false);

    /* Restore current snapshot if requested: */
    if (vboxGlobal().shouldRestoreCurrentSnapshot())
    {
        /* Create temporary session: */
        CSession session = vboxGlobal().openSession(strID, KLockType_VM);
        if (session.isNull())
            return false;

        /* Which VM we operate on? */
        CMachine machine = session.GetMachine();
        /* Which snapshot we are restoring? */
        CSnapshot snapshot = machine.GetCurrentSnapshot();

        /* Prepare restore-snapshot progress: */
        CProgress progress = machine.RestoreSnapshot(snapshot);
        if (!machine.isOk())
            return msgCenter().cannotRestoreSnapshot(machine, snapshot.GetName(), machine.GetName());

        /* Show the snapshot-discarding progress: */
        msgCenter().showModalProgressDialog(progress, machine.GetName(), ":/progress_snapshot_discard_90px.png");
        if (progress.GetResultCode() != 0)
            return msgCenter().cannotRestoreSnapshot(progress, snapshot.GetName(), machine.GetName());

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

        /* Clear snapshot-restoring request: */
        vboxGlobal().setShouldRestoreCurrentSnapshot(false);
    }

    /* For separate process we should launch VM before UI: */
    if (vboxGlobal().isSeparateProcess())
    {
        /* Get corresponding machine: */
        CMachine machine = vboxGlobal().virtualBox().FindMachine(vboxGlobal().managedVMUuid());
        AssertMsgReturn(!machine.isNull(), ("VBoxGlobal::managedVMUuid() should have filter that case before!\n"), false);

        /* Try to launch corresponding machine: */
        if (!vboxGlobal().launchMachine(machine, VBoxGlobal::LaunchMode_Separate))
            return false;
    }

    /* Try to create machine UI: */
    return create();
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
0
void VBoxSnapshotsWgt::sltRestoreSnapshot(bool fSuppressNonCriticalWarnings /* = false*/)
{
    /* Get currently chosen item: */
    SnapshotWgtItem *pItem = mTreeWidget->currentItem() ? static_cast<SnapshotWgtItem*>(mTreeWidget->currentItem()) : 0;
    AssertReturn(pItem, (void)0);
    /* Detemine snapshot id: */
    QString strSnapshotId = pItem->snapshotId();
    AssertReturn(!strSnapshotId.isNull(), (void)0);
    /* Get currently desired snapshot: */
    CSnapshot snapshot = mMachine.FindSnapshot(strSnapshotId);

    /* Ask the user if he really wants to restore the snapshot: */
    int iResultCode = AlertButton_Ok;
    if (!fSuppressNonCriticalWarnings || mMachine.GetCurrentStateModified())
    {
        iResultCode = msgCenter().confirmSnapshotRestoring(snapshot.GetName(), mMachine.GetCurrentStateModified());
        if (iResultCode & AlertButton_Cancel)
            return;
    }

    /* If user also confirmed new snapshot creation: */
    if (iResultCode & AlertOption_CheckBox)
    {
        /* Take snapshot of changed current state: */
        mTreeWidget->setCurrentItem(curStateItem());
        if (!takeSnapshot())
            return;
    }

    /* Open a direct session (this call will handle all errors): */
    CSession session = vboxGlobal().openSession(mMachineId);
    if (session.isNull())
        return;

    /* Restore chosen snapshot: */
    CConsole console = session.GetConsole();
    CProgress progress = console.RestoreSnapshot(snapshot);
    if (console.isOk())
    {
        msgCenter().showModalProgressDialog(progress, mMachine.GetName(), ":/progress_snapshot_restore_90px.png");
        if (progress.GetResultCode() != 0)
            msgCenter().cannotRestoreSnapshot(progress, snapshot.GetName(), mMachine.GetName());
    }
    else
        msgCenter().cannotRestoreSnapshot(console, snapshot.GetName(), mMachine.GetName());

    /* Unlock machine finally: */
    session.UnlockMachine();
}
Ejemplo n.º 12
0
void VBoxSnapshotsWgt::sltDeleteSnapshot()
{
    SnapshotWgtItem *item = !mTreeWidget->currentItem() ? 0 :
        static_cast <SnapshotWgtItem*> (mTreeWidget->currentItem());
    AssertReturn (item, (void) 0);

    QString snapId = item->snapshotId();
    AssertReturn (!snapId.isNull(), (void) 0);
    CSnapshot snapshot = mMachine.FindSnapshot(snapId);

    if (!msgCenter().confirmSnapshotRemoval(snapshot.GetName()))
        return;

    /** @todo check available space on the target filesystem etc etc. */
#if 0
    if (!msgCenter().warnAboutSnapshotRemovalFreeSpace(snapshot.GetName(),
                                                       "/home/juser/.VirtualBox/Machines/SampleVM/Snapshots/{01020304-0102-0102-0102-010203040506}.vdi",
                                                       "59 GiB",
                                                       "15 GiB"))
        return;
#endif

    /* Open a direct session (this call will handle all errors) */
    bool busy = mSessionState != KSessionState_Unlocked;
    CSession session;
    if (busy)
        session = vboxGlobal().openExistingSession(mMachineId);
    else
        session = vboxGlobal().openSession(mMachineId);
    if (session.isNull())
        return;

    CConsole console = session.GetConsole();
    CProgress progress = console.DeleteSnapshot (snapId);
    if (console.isOk())
    {
        /* Show the progress dialog */
        msgCenter().showModalProgressDialog(progress, mMachine.GetName(), ":/progress_snapshot_discard_90px.png");

        if (progress.GetResultCode() != 0)
            msgCenter().cannotRemoveSnapshot(progress,  snapshot.GetName(), mMachine.GetName());
    }
    else
        msgCenter().cannotRemoveSnapshot(console,  snapshot.GetName(), mMachine.GetName());

    session.UnlockMachine();
}
Ejemplo n.º 13
0
int UIDnDHandler::retrieveDataInternal(      Qt::DropAction    dropAction,
                                       const QString          &strMIMEType,
                                             QVector<uint8_t> &vecData)
{
    LogFlowFunc(("Retrieving data as '%s', dropAction=%d\n", qPrintable(strMIMEType), dropAction));

    int rc = VINF_SUCCESS;

    /* Indicate to the guest that we have dropped the data on the host.
     * The guest then will initiate the actual "drop" operation into our proxy on the guest. */
    Assert(!m_dndSource.isNull());
    CProgress progress = m_dndSource.Drop(strMIMEType,
                                          UIDnDHandler::toVBoxDnDAction(dropAction));
    LogFlowFunc(("Source: isOk=%RTbool\n", m_dndSource.isOk()));
    if (m_dndSource.isOk())
    {
        /* Send a mouse event with released mouse buttons into the guest that triggers
         * the "drop" event in our proxy window on the guest. */
        AssertPtr(m_pSession);
        m_pSession->mouse().PutMouseEvent(0, 0, 0, 0, 0);

        msgCenter().showModalProgressDialog(progress,
                                            tr("Retrieving data ..."), ":/progress_dnd_gh_90px.png",
                                            m_pParent);

        LogFlowFunc(("Progress: fCanceled=%RTbool, fCompleted=%RTbool, isOk=%RTbool, hrc=%Rhrc\n",
                     progress.GetCanceled(), progress.GetCompleted(), progress.isOk(), progress.GetResultCode()));

        if (!progress.GetCanceled())
        {
            rc =   (   progress.isOk()
                    && progress.GetResultCode() == 0)
                 ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */

            if (RT_SUCCESS(rc))
            {
                /* After we successfully retrieved data from the source we query it from Main. */
                vecData = m_dndSource.ReceiveData(); /** @todo QVector.size() is "int" only!? */
                if (vecData.isEmpty())
                    rc = VERR_NO_DATA;
            }
            else
                msgCenter().cannotDropDataToHost(progress, m_pParent);
        }
        else /* Don't pop up a message. */
            rc = VERR_CANCELLED;
    }
    else
    {
        msgCenter().cannotDropDataToHost(m_dndSource, m_pParent);
        rc = VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */
    }

    setMode(DNDMODE_UNKNOWN);

    LogFlowFuncLeaveRC(rc);
    return rc;
}
Ejemplo n.º 14
0
Qt::DropAction UIDnDHandler::dragHGDrop(CGuest &guest, ulong screenId, int x, int y, Qt::DropAction proposedAction, Qt::DropActions possibleActions, const QMimeData *pMimeData, QWidget *pParent /* = 0 */)
{
    /* The format the guest requests. */
    QString format;
    /* Ask the guest for dropping data. */
    KDragAndDropAction result = guest.DragHGDrop(screenId,
                                                 x,
                                                 y,
                                                 toVBoxDnDAction(proposedAction),
                                                 toVBoxDnDActions(possibleActions),
                                                 pMimeData->formats().toVector(), format);
    /* Has the guest accepted the drop event? */
    if (result != KDragAndDropAction_Ignore)
    {
        /* Get the actually data */
        const QByteArray &d = pMimeData->data(format);
        if (   !d.isEmpty()
            && !format.isEmpty())
        {
            /* We need the data in the vector format. */
            QVector<uint8_t> dv(d.size());
            memcpy(dv.data(), d.constData(), d.size());

            CProgress progress = guest.DragHGPutData(screenId, format, dv);
            if (guest.isOk())
            {
                msgCenter().showModalProgressDialog(progress, tr("Dropping data ..."), ":/progress_dnd_hg_90px.png", pParent);
                if (!progress.GetCanceled() && (!progress.isOk() || progress.GetResultCode() != 0))
                {
                    msgCenter().cannotDropData(progress, pParent);
                    result = KDragAndDropAction_Ignore;
                }
            }
            else
            {
                msgCenter().cannotDropData(guest, pParent);
                result = KDragAndDropAction_Ignore;
            }
        }
    }

    return toQtDnDAction(result);
}
Ejemplo n.º 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);
}
Ejemplo n.º 16
0
void UINewVMWzdPage4::ensureNewHardDiskDeleted()
{
    if (m_HardDisk.isNull())
        return;

    QString id = m_HardDisk.GetId();

    bool success = false;

    CProgress progress = m_HardDisk.DeleteStorage();
    if (m_HardDisk.isOk())
    {
        msgCenter().showModalProgressDialog(progress, windowTitle(), ":/progress_media_delete_90px.png", this, true);
        if (progress.isOk() && progress.GetResultCode() == S_OK)
            success = true;
    }

    if (success)
        vboxGlobal().removeMedium(VBoxDefs::MediumType_HardDisk, id);
    else
        msgCenter().cannotDeleteHardDiskStorage(this, m_HardDisk, progress);

    m_HardDisk.detach();
}
Ejemplo n.º 17
0
bool UIWizardExportApp::exportVMs(CAppliance &appliance)
{
    /* Write the appliance: */
    CProgress progress = appliance.Write(field("format").toString(), field("manifestSelected").toBool() /* fManifest */, uri());
    bool fResult = appliance.isOk();
    if (fResult)
    {
        /* Show some progress, so the user know whats going on: */
        msgCenter().showModalProgressDialog(progress, QApplication::translate("UIWizardExportApp", "Exporting Appliance ..."),
                                            ":/progress_export_90px.png", this);
        if (progress.GetCanceled())
            return false;
        if (!progress.isOk() || progress.GetResultCode() != 0)
        {
            msgCenter().cannotExportAppliance(progress, appliance.GetPath(), this);
            return false;
        }
        else
            return true;
    }
    if (!fResult)
        msgCenter().cannotExportAppliance(appliance, this);
    return false;
}
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);
                    }
                }
            }
        }
Ejemplo n.º 19
0
//////////////////////////////////////////////////////////////////////////
// 
//  Function Name:  WindowProc 
//  Description:    Used for handling windows messages 
//  Parameters:     UINT message
//                  WPARAM wParam
//                  LPARAM lparam
//                  char *cpBuffer               
//  Returns:        BOOL
//  Summary:        This functions gets called in the CPictureWizardDlg's WindowProc
//                  Within the CPictureWizardDlg's WindowProc functions, we are 
//                  also calling this function since there is a possibility that 
//                  the release button was pressed.  The 'message' tells us what sort of 
//                  message was generated prior to calling WindowProc.  If a picture is 
//                  taken, the ReleaseCallBackFunction will be called setting the message
//                  to g_ReleaseOnMessage 
//  Author:         CannonSDK
//                           
///////////////////////////////////////////////////////////////////////////
BOOL CCameraConnect::WindowProc(UINT message, WPARAM wParam, LPARAM lParam, char* cpBuffer)
{
	cdError		err;
	BOOL		fRes;
	CProgress	CProg;
	//char		szSavePath[MAX_PATH];
	
	cdUInt32	NumData;
	
	if( message == g_ReleaseOnMessage )
	{
		/* UI is locked so that information may not be changed. */
		err = CDLockUI( m_hSource );
		if( GETERRORID(err) != cdOK )
		{
			//goto	camerr;
		}
		
		/* It sets up so that a complete message may be disregarded. */
		m_fProgramRelease = TRUE;
	
		/* A special camera ends a view finder. */
		if( m_RelControlCap&cdRELEASE_CONTROL_CAP_ABORT_VIEWFINDER )
		{
			if( m_fVFEnd )
			{
				/* A view finder is ended. */
				err = CDTermViewfinder( m_hSource );
				if( GETERRORID(err) != cdOK )
				{
					//goto	camerr;
				}
		
				/* A thread is ended. */
				m_fVFEnd = FALSE;
				g_CpVFThread->ResumeThread();
				WaitForSingleObject( g_CpVFThread->m_hThread, INFINITE );
				
				// this is something that will have to be done on the dlg
				//m_CViewFinder.SetWindowText( "Start" );				
				//Invalidate();
				//UpdateWindow();
			}
		}
		
		/* A photograph is taken. */
		NumData = 0;		
		err = CDRelease( m_hSource, FALSE, NULL, NULL, cdPROG_NO_REPORT, &NumData );
		if( GETERRORID(err) != cdOK )
		{
			//goto	camerr;
		}
		
		/* The directory to save is acquired. */
		// this is actually done in the dlg
		//GetSavePath( szSavePath, MAX_PATH );
		
		//szSavePath = cpBuffer;

		/* The photoed picture is saved. */
		//fRes = CProg.GetReleaseData( m_hSource, NumData, cpBuffer );
		
		// Determine if we should take the left picture or the right 
		if (pCPictureWizardDlg->horizontal) // left picture
		{
			//to indicate that horizontal picture is taken
			pCPictureWizardDlg->horizontal = false;
			
			//set the file name for the horizontal(true) picture 
			SetFileName(true);
			fRes = CProg.GetReleaseData( m_hSource, NumData, FileName, this );

			//display horizonal picture in left box
			if (pCPictureWizardDlg->m_jpgLeft.Load(_T(FileName)))
			{	
				pCPictureWizardDlg->m_jpgLeft.Scale(PICTURE_WINDOW_WIDTH, PICTURE_WINDOW_HEIGHT);
				pCPictureWizardDlg->m_jpgLeft.Draw();
			}
		}
		else // right picture
		{
			//set the file name for the vertical (false) picture
			SetFileName(false);
			fRes = CProg.GetReleaseData( m_hSource, NumData, FileName, this );

			//diplay vertical picture in right box
			if (pCPictureWizardDlg->m_jpgRight.Load(_T(FileName)))
			{	
				pCPictureWizardDlg->m_jpgRight.Scale(PICTURE_WINDOW_WIDTH, PICTURE_WINDOW_HEIGHT);
				pCPictureWizardDlg->m_jpgRight.Draw();
			}
		 
		}

		if( !fRes )
		{
			//goto	apierr;
		}
		else if( GETERRORID(CProg.m_LastErr) == cdOPERATION_CANCELLED )
		{
			m_fProgramRelease = FALSE;
			CDUnlockUI( m_hSource );
			return	TRUE;
		}
		else if( GETERRORID(CProg.m_LastErr) != cdOK )
		{
			err = CProg.m_LastErr;
			//goto	camerr;
		}
		
		/* The lock of UI is canceled. */
		err = CDUnlockUI( m_hSource );
		if( GETERRORID(err) != cdOK )
		{
			//goto	camerr;
		}
		
		/* It sets up so that a complete message may be received. */
		m_fProgramRelease = FALSE;
		
		//bPictDone = TRUE;
		//PictureDoneWait();
		return	TRUE;
	}
	return TRUE;	
}
Ejemplo n.º 20
0
Qt::DropAction UIDnDHandler::dragDrop(ulong screenID, int x, int y,
                                      Qt::DropAction proposedAction, Qt::DropActions possibleActions,
                                      const QMimeData *pMimeData)
{
    LogFlowFunc(("enmOpMode=%RU32, screenID=%RU32, x=%d, y=%d, action=%ld\n",
                 m_enmOpMode, screenID, x, y, toVBoxDnDAction(proposedAction)));

    if (m_enmOpMode != DNDMODE_HOSTTOGUEST)
        return Qt::IgnoreAction;

    /* The format the guest requests. */
    QString strFormat;
    /* Ask the guest for dropping data. */
    KDnDAction enmResult = m_dndTarget.Drop(screenID,
                                            x,
                                            y,
                                            toVBoxDnDAction(proposedAction),
                                            toVBoxDnDActions(possibleActions),
                                            pMimeData->formats().toVector(), strFormat);

    /* Has the guest accepted the drop event? */
    if (   m_dndTarget.isOk()
        && enmResult != KDnDAction_Ignore)
    {
        LogFlowFunc(("strFormat=%s ...\n", strFormat.toUtf8().constData()));

        QByteArray arrBytes;

        /*
         * Does the host support the format requested by the guest?
         * Lookup the format in the MIME data object.
         */
        AssertPtr(pMimeData);
        if (pMimeData->formats().indexOf(strFormat) >= 0)
        {
            arrBytes = pMimeData->data(strFormat);
            Assert(!arrBytes.isEmpty());
        }
        /*
         * The host does not support the format requested by the guest.
         * This can happen if the host wants to send plan text, for example, but
         * the guest requested something else, e.g. an URI list.
         *
         * In that case dictate the guest to use a fixed format from the host,
         * so instead returning the requested URI list, return the original
         * data format from the host. The guest has to try to deal with that then.
         **/
        else
        {
            LogRel3(("DnD: Guest requested a different format '%s'\n", strFormat.toUtf8().constData()));
            LogRel3(("DnD: The host offered:\n"));
#if 0
            for (QStringList::iterator itFmt  = pMimeData->formats().begin();
                                       itFmt != pMimeData->formats().end(); itFmt++)
            {
                QString strTemp = *itFmt;
                LogRel3(("DnD: \t%s\n", strTemp.toUtf8().constData()));
            }
#endif
            if (pMimeData->hasText())
            {
                LogRel3(("DnD: Converting data to text ...\n"));
                arrBytes  = pMimeData->text().toUtf8();
                strFormat = "text/plain;charset=utf-8";
            }
            else
            {
                LogRel(("DnD: Error: Could not convert host format to guest format\n"));
                enmResult = KDnDAction_Ignore;
            }
        }

        if (arrBytes.size()) /* Anything to send? */
        {
            /* Convert data to a vector. */
            QVector<uint8_t> vecData(arrBytes.size()); /** @todo Can this throw or anything? */
            AssertReleaseMsg(vecData.size() == arrBytes.size(), ("Drag and drop format buffer size does not match"));
            memcpy(vecData.data(), arrBytes.constData(), arrBytes.size());

            /* Send data to the guest. */
            LogRel3(("DnD: Host is sending %d bytes of data as '%s'\n", vecData.size(), strFormat.toUtf8().constData()));
            CProgress progress = m_dndTarget.SendData(screenID, strFormat, vecData);

            if (m_dndTarget.isOk())
            {
                msgCenter().showModalProgressDialog(progress,
                                                    tr("Dropping data ..."), ":/progress_dnd_hg_90px.png",
                                                    m_pParent);

                LogFlowFunc(("Transfer fCompleted=%RTbool, fCanceled=%RTbool, hr=%Rhrc\n",
                             progress.GetCompleted(), progress.GetCanceled(), progress.GetResultCode()));

                BOOL fCanceled = progress.GetCanceled();
                if (   !fCanceled
                    && (   !progress.isOk()
                        ||  progress.GetResultCode() != 0))
                {
                    msgCenter().cannotDropDataToGuest(progress, m_pParent);
                    enmResult = KDnDAction_Ignore;
                }
            }
            else
            {
                msgCenter().cannotDropDataToGuest(m_dndTarget, m_pParent);
                enmResult = KDnDAction_Ignore;
            }
        }
        else /* Error. */
            enmResult = KDnDAction_Ignore;
    }

    /*
     * Since the mouse button has been release this in any case marks
     * the end of the current transfer direction. So reset the current
     * mode as well here.
     */
    setOpMode(DNDMODE_UNKNOWN);

    return toQtDnDAction(enmResult);
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
0
//////////////////////////////////////////////////////////////////////////
// 
//  Function Name:  SetReleaseState 
//  Description:    Takes and stores picture
//  Parameters:                    
//  Returns:        void
//  Summary:        When this function is called, the picture is first taken
//                  and then stored by calling GetReleaseData.   
//  Author:         CannonSDK
//                           
///////////////////////////////////////////////////////////////////////////
void CCameraConnect::StartRelease(char* szSavePath)
{
	cdError		err;
	BOOL		fRes;
	CProgress	CProg;
	//char		szSavePath[MAX_PATH];
	cdUInt32	NumData;
	
	/* UI is locked so that information may not be changed. */
	err = CDLockUI( m_hSource );
	if( GETERRORID(err) != cdOK )
	{
	//	goto	camerr;
	}
	
	/* It sets up so that a complete message may be disregarded. */
	m_fProgramRelease = TRUE;
	
	/* A special camera ends a view finder. */
	if( m_RelControlCap&cdRELEASE_CONTROL_CAP_ABORT_VIEWFINDER )
	{
		if( m_fVFEnd )
		{
			/* A view finder is ended. */
			err = CDTermViewfinder( m_hSource );
			if( GETERRORID(err) != cdOK )
			{
			//	goto	camerr;
			}
			
			/* A thread is ended. */
			m_fVFEnd = FALSE;
			g_CpVFThread->ResumeThread();
			WaitForSingleObject( g_CpVFThread->m_hThread, INFINITE );
			
			//m_CViewFinder.SetWindowText( "Start" );
//			Invalidate();
//			UpdateWindow();	
		}
	}
	
	/* A photograph is taken. */
	NumData = 0;
	err = CDRelease( m_hSource, FALSE, NULL, NULL, cdPROG_NO_REPORT, &NumData );
	if( GETERRORID(err) != cdOK )
	{
	//	goto	camerr;
	}
	
	/* The directory to save is acquired. */
	//GetSavePath( szSavePath, MAX_PATH );
	
	/* The photoed picture is saved. */
	fRes = CProg.GetReleaseData( m_hSource, NumData, szSavePath, this );
	if( !fRes )
	{
	//	goto	apierr;
	}
	else if( GETERRORID(CProg.m_LastErr) == cdOPERATION_CANCELLED )
	{
		m_fProgramRelease = FALSE;
		CDUnlockUI( m_hSource );
		return;
	}
	else if( GETERRORID(CProg.m_LastErr) != cdOK )
	{
		err = CProg.m_LastErr;
	//	goto	camerr;
	}
	
	/* The lock of UI is canceled. */
	err = CDUnlockUI( m_hSource );
	if( GETERRORID(err) != cdOK )
	{
	//	goto	camerr;
	}
	
	/* It sets up so that a complete message may be received. */
	m_fProgramRelease = FALSE;
	return;
	
	


}
void CEmpBalanceCount::OnOK() //查询选择
{

	CString strSql,str1;
	long year;
	pc->GetLBText(pc->GetCurSel(),str1);
	year=atol(str1);

	CProgress pd;
	pd.flagRun=false; //指示运行前是否弹出对话框
//	pd.strNotify="是否确定要进行年度结转充值,每年度只允许进行一次充值!!!";
	pd.pThreadFunction=CProgress::createBalanceCount;
	pd.strView="正在进行查询,请稍候...";
	pd.iYear = year;
	pd.DoModal();

	
	if( pd.flagRun ){
		AfxMessageBox("生成结算表时出错!!!");
		return;
	}

	
	long row,cols,i,col;
	
	m_grid.Clear();
	m_grid.SetRows(2);
	CString px[]={"分类项目","在职","建国后退休","建国前退休","合计"};

	long pl[]={2800,1600,1600,1600,1600,2000,1500,2200,1000,1000,1000,1000};
	CPeculiarInput::SetGridHead(px,pl,m_grid,sizeof(px)/sizeof(CString),1,0);
	
	m_grid.SetColAlignmentFixed(0,1); //首列居左对齐
	
	try{
		strSql.Format("SELECT * FROM v_balance_count");
		recSet->Open(_bstr_t(strSql),(IDispatch*)HospitalConnect,adOpenDynamic,adLockOptimistic,adCmdText); 
		cols=recSet->GetFields()->Count;
		row=1;
		double dX;
		while(!recSet->adoEOF){
			col=0;

			m_grid.SetMergeRow(row,false); 
			for(i=0;i<cols;i++)
			{
				strSql=(char*)_bstr_t(recSet->GetFields()->GetItem(_variant_t(i))->Value.vt==VT_NULL?" ":recSet->GetFields()->GetItem(_variant_t(i))->Value);
				if( row != 1 && i != 0 ) str1.Format("%.2f",atof(strSql)); //第一行人数不保留小数点,后面全部留两位小数点
				else str1=strSql;
				m_grid.SetTextMatrix(row,col++,str1);
				
			}
			row++;
			m_grid.AddItem("",_variant_t(row));
			recSet->MoveNext();
			
		}
		recSet->Close();

		m_grid.SetRedraw(true);
		m_grid.RemoveItem(row);
		
	}
	catch(_com_error e)
	{
		AfxMessageBox(strSql);
		recSet->Close();
	
		return ;
	}	
}
/**
 * Attempt the actual installation.
 *
 * This code is shared by UIGlobalSettingsExtension::sltInstallPackage and UISelectorWindow::sltOpenUrls.
 *
 * @param   strFilePath     The path to the tarball.
 * @param   strDigest       The digest of the file (SHA-256). Empty string if no
 *                          digest was performed.
 * @param   pParent         The parent widget.
 * @param   pstrExtPackName Where to return the extension pack name. Optional.
 */
/*static*/ void UIGlobalSettingsExtension::doInstallation(QString const &strFilePath, QString const &strDigest,
                                                          QWidget *pParent, QString *pstrExtPackName)
{
    /*
     * Open the extpack tarball via IExtPackManager.
     */
    CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager();
    CExtPackFile extPackFile;
    if (strDigest.isEmpty())
        extPackFile = manager.OpenExtPackFile(strFilePath);
    else
    {
        QString strFileAndHash = QString("%1::SHA-256=%2").arg(strFilePath).arg(strDigest);
        extPackFile = manager.OpenExtPackFile(strFileAndHash);
    }
    if (!manager.isOk())
    {
        msgCenter().cannotOpenExtPack(strFilePath, manager, pParent);
        return;
    }

    if (!extPackFile.GetUsable())
    {
        msgCenter().badExtPackFile(strFilePath, extPackFile, pParent);
        return;
    }

    QString strPackName = extPackFile.GetName();
    QString strPackDescription = extPackFile.GetDescription();
    QString strPackVersion = QString("%1r%2%3").arg(extPackFile.GetVersion()).arg(extPackFile.GetRevision()).arg(extPackFile.GetEdition());

    /*
     * Check if there is a version of the extension pack already
     * installed on the system and let the user decide what to do about
     * it.
     */
    CExtPack extPackCur = manager.Find(strPackName);
    bool fReplaceIt = extPackCur.isOk();
    if (fReplaceIt)
    {
        QString strPackVersionCur = QString("%1r%2%3").arg(extPackCur.GetVersion()).arg(extPackCur.GetRevision()).arg(extPackCur.GetEdition());
        if (!msgCenter().confirmReplacePackage(strPackName, strPackVersion, strPackVersionCur, strPackDescription, pParent))
            return;
    }
    /*
     * If it's a new package just ask for general confirmation.
     */
    else
    {
        if (!msgCenter().confirmInstallingPackage(strPackName, strPackVersion, strPackDescription, pParent))
            return;
    }

    /*
     * Display the license dialog if required by the extension pack.
     */
    if (extPackFile.GetShowLicense())
    {
        QString strLicense = extPackFile.GetLicense();
        VBoxLicenseViewer licenseViewer(pParent);
        if (licenseViewer.showLicenseFromString(strLicense) != QDialog::Accepted)
            return;
    }

    /*
     * Install the selected package.
     *
     * Set the package name return value before doing this as the caller should
     * do a refresh even on failure.
     */
    QString displayInfo;
#ifdef RT_OS_WINDOWS
    if (pParent)
        displayInfo.sprintf("hwnd=%#llx", (uint64_t)(uintptr_t)pParent->winId());
#endif
    CProgress progress = extPackFile.Install(fReplaceIt, displayInfo);
    if (extPackFile.isOk())
    {
        if (progress.isNull())
            msgCenter().notifyAboutExtPackInstalled(strPackName, pParent);
        else
        {
            msgCenter().showModalProgressDialog(progress, tr("Extensions"));
            if (!progress.GetCanceled())
            {
                if (progress.isOk() && progress.GetResultCode() == 0)
                    msgCenter().notifyAboutExtPackInstalled(strPackName, pParent);
                else
                    msgCenter().cannotInstallExtPack(strFilePath, extPackFile, progress, pParent);
            }
        }
    }
    else
        msgCenter().cannotInstallExtPack(strFilePath, extPackFile, progress, pParent);

    if (pstrExtPackName)
        *pstrExtPackName = strPackName;
}
Ejemplo n.º 25
0
bool UIWizardExportApp::exportVMs(CAppliance &appliance)
{
    /* Get the map of the password IDs: */
    EncryptedMediumMap encryptedMediums;
    foreach (const QString &strPasswordId, appliance.GetPasswordIds())
        foreach (const QString &strMediumId, appliance.GetMediumIdsForPasswordId(strPasswordId))
            encryptedMediums.insert(strPasswordId, strMediumId);

    /* Ask for the disk encryption passwords if necessary: */
    if (!encryptedMediums.isEmpty())
    {
        /* Create corresponding dialog: */
        QPointer<UIAddDiskEncryptionPasswordDialog> pDlg =
             new UIAddDiskEncryptionPasswordDialog(this,
                                                   window()->windowTitle(),
                                                   encryptedMediums);

        /* Execute the dialog: */
        if (pDlg->exec() == QDialog::Accepted)
        {
            /* Acquire the passwords provided: */
            const EncryptionPasswordMap encryptionPasswords = pDlg->encryptionPasswords();

            /* Delete the dialog: */
            delete pDlg;

            /* Make sure the passwords were really provided: */
            AssertReturn(!encryptionPasswords.isEmpty(), false);

            /* Provide appliance with passwords if possible: */
            appliance.AddPasswords(encryptionPasswords.keys().toVector(),
                                   encryptionPasswords.values().toVector());
            if (!appliance.isOk())
            {
                /* Warn the user about failure: */
                msgCenter().cannotAddDiskEncryptionPassword(appliance);

                return false;
            }
        }
        else
        {
            /* Any modal dialog can be destroyed in own event-loop
             * as a part of application termination procedure..
             * We have to check if the dialog still valid. */
            if (pDlg)
            {
                /* Delete the dialog: */
                delete pDlg;
            }

            return false;
        }
    }

    /* Write the appliance: */
    QVector<KExportOptions> options;
    if (field("manifestSelected").toBool())
        options.append(KExportOptions_CreateManifest);
    CProgress progress = appliance.Write(field("format").toString(), options, uri());
    bool fResult = appliance.isOk();
    if (fResult)
    {
        /* Show some progress, so the user know whats going on: */
        msgCenter().showModalProgressDialog(progress, QApplication::translate("UIWizardExportApp", "Exporting Appliance ..."),
                                            ":/progress_export_90px.png", this);
        if (progress.GetCanceled())
            return false;
        if (!progress.isOk() || progress.GetResultCode() != 0)
        {
            msgCenter().cannotExportAppliance(progress, appliance.GetPath(), this);
            return false;
        }
        else
            return true;
    }
    if (!fResult)
        msgCenter().cannotExportAppliance(appliance, this);
    return false;
}
Ejemplo n.º 26
0
bool UIWizardExportApp::exportAppliance()
{
    /* Get export appliance widget: */
    UIApplianceExportEditorWidget *pExportApplianceWidget = field("applianceWidget").value<ExportAppliancePointer>();
    /* Fetch all settings from the appliance editor. */
    pExportApplianceWidget->prepareExport();
    /* Get the appliance. */
    CAppliance *pAppliance = pExportApplianceWidget->appliance();
    /* We need to know every filename which will be created, so that we can
     * ask the user for confirmation of overwriting. For that we iterating
     * over all virtual systems & fetch all descriptions of the type
     * HardDiskImage. Also add the manifest file to the check. In the ova
     * case only the target file itself get checked. */
    QFileInfo fi(field("path").toString());
    QVector<QString> files;
    files << fi.fileName();
    if (fi.suffix().toLower() == "ovf")
    {
        if (field("manifestSelected").toBool())
            files << fi.baseName() + ".mf";
        CVirtualSystemDescriptionVector vsds = pAppliance->GetVirtualSystemDescriptions();
        for (int i = 0; i < vsds.size(); ++ i)
        {
            QVector<KVirtualSystemDescriptionType> types;
            QVector<QString> refs, origValues, configValues, extraConfigValues;
            vsds[i].GetDescriptionByType(KVirtualSystemDescriptionType_HardDiskImage, types,
                                         refs, origValues, configValues, extraConfigValues);
            foreach (const QString &s, origValues)
                files << QString("%2").arg(s);
        }
    }
    CVFSExplorer explorer = pAppliance->CreateVFSExplorer(uri(false /* fWithFile */));
    CProgress progress = explorer.Update();
    bool fResult = explorer.isOk();
    if (fResult)
    {
        /* Show some progress, so the user know whats going on: */
        msgCenter().showModalProgressDialog(progress, QApplication::translate("UIWizardExportApp", "Checking files ..."),
                                            ":/refresh_32px.png", this);
        if (progress.GetCanceled())
            return false;
        if (!progress.isOk() || progress.GetResultCode() != 0)
        {
            msgCenter().cannotCheckFiles(progress, this);
            return false;
        }
    }
    QVector<QString> exists = explorer.Exists(files);
    /* Check if the file exists already, if yes get confirmation for overwriting from the user. */
    if (!msgCenter().confirmOverridingFiles(exists, this))
        return false;
    /* Ok all is confirmed so delete all the files which exists: */
    if (!exists.isEmpty())
    {
        CProgress progress1 = explorer.Remove(exists);
        fResult = explorer.isOk();
        if (fResult)
        {
            /* Show some progress, so the user know whats going on: */
            msgCenter().showModalProgressDialog(progress1, QApplication::translate("UIWizardExportApp", "Removing files ..."),
                                                ":/vm_delete_32px.png", this);
            if (progress1.GetCanceled())
                return false;
            if (!progress1.isOk() || progress1.GetResultCode() != 0)
            {
                msgCenter().cannotRemoveFiles(progress1, this);
                return false;
            }
        }
    }

    /* Export the VMs, on success we are finished: */
    if (exportVMs(*pAppliance))
    {
#if 0
        /* Save attributes to GUI extra data: */
        StorageType storageType = field("storageType").value<StorageType>();
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_StorageType, QString::number(storageType));
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_Username, m_pLeUsername->text());
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_Hostname, m_pLeHostname->text());
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_Bucket, m_pLeBucket->text());
#endif
        return true;
    }
    return false;
}
Ejemplo n.º 27
0
bool VBoxSnapshotsWgt::takeSnapshot()
{
    /* Prepare result: */
    bool fIsValid = true;

    /* Get currently chosen item: */
    SnapshotWgtItem *pItem = mTreeWidget->currentItem() ? static_cast<SnapshotWgtItem*>(mTreeWidget->currentItem()) : 0;
    AssertReturn(pItem, (bool)0);

    /* Open a session to work with corresponding VM: */
    CSession session;
    if (mSessionState != KSessionState_Unlocked)
        session = vboxGlobal().openExistingSession(mMachineId);
    else
        session = vboxGlobal().openSession(mMachineId);
    fIsValid = !session.isNull();

    if (fIsValid)
    {
        /* Get corresponding console object also: */
        CConsole console = session.GetConsole();
        /* Remember runtime state: */
        bool fAtRuntime = mMachine.GetState() == KMachineState_Running;
        /* Remember paused state: */
        bool fWasPaused = mMachine.GetState() == KMachineState_Paused ||
                          mMachine.GetState() == KMachineState_TeleportingPausedVM;

        /* Pause VM if necessary: */
        if (fIsValid && fAtRuntime && !fWasPaused)
        {
            /* Pausing VM: */
            console.Pause();
            if (!console.isOk())
            {
                msgCenter().cannotPauseMachine(console);
                fIsValid = false;
            }
        }

        if (fIsValid)
        {
            /* Create take-snapshot dialog: */
            QWidget *pDlgParent = windowManager().realParentWindow(this);
            QPointer<VBoxTakeSnapshotDlg> pDlg = new VBoxTakeSnapshotDlg(pDlgParent, mMachine);
            windowManager().registerNewParent(pDlg, pDlgParent);

            /* Assign corresponding icon: */
            pDlg->mLbIcon->setPixmap(vboxGlobal().vmGuestOSTypeIcon(mMachine.GetOSTypeId()));

            /* Search for the max available snapshot index: */
            int iMaxSnapShotIndex = 0;
            QString snapShotName = tr("Snapshot %1");
            QRegExp regExp(QString("^") + snapShotName.arg("([0-9]+)") + QString("$"));
            QTreeWidgetItemIterator iterator(mTreeWidget);
            while (*iterator)
            {
                QString snapShot = static_cast<SnapshotWgtItem*>(*iterator)->text(0);
                int pos = regExp.indexIn(snapShot);
                if (pos != -1)
                    iMaxSnapShotIndex = regExp.cap(1).toInt() > iMaxSnapShotIndex ? regExp.cap(1).toInt() : iMaxSnapShotIndex;
                ++iterator;
            }
            pDlg->mLeName->setText(snapShotName.arg(iMaxSnapShotIndex + 1));

            /* Exec the dialog: */
            bool fDialogAccepted = pDlg->exec() == QDialog::Accepted;

            /* Is the dialog still valid? */
            if (pDlg)
            {
                /* Acquire variables: */
                QString strSnapshotName = pDlg->mLeName->text().trimmed();
                QString strSnapshotDescription = pDlg->mTeDescription->toPlainText();

                /* Destroy dialog early: */
                delete pDlg;

                /* Was the dialog accepted? */
                if (fDialogAccepted)
                {
                    /* Prepare the take-snapshot progress: */
                    CProgress progress = console.TakeSnapshot(strSnapshotName, strSnapshotDescription);
                    if (console.isOk())
                    {
                        /* Show the take-snapshot progress: */
                        msgCenter().showModalProgressDialog(progress, mMachine.GetName(), ":/progress_snapshot_create_90px.png");
                        if (!progress.isOk() || progress.GetResultCode() != 0)
                        {
                            msgCenter().cannotTakeSnapshot(progress, mMachine.GetName());
                            fIsValid = false;
                        }
                    }
                    else
                    {
                        msgCenter().cannotTakeSnapshot(console, mMachine.GetName());
                        fIsValid = false;
                    }
                }
                else
                    fIsValid = false;
            }
            else
                fIsValid = false;
        }

        /* Resume VM if necessary: */
        if (fIsValid && fAtRuntime && !fWasPaused)
        {
            /* Resuming VM: */
            console.Resume();
            if (!console.isOk())
            {
                msgCenter().cannotResumeMachine(console);
                fIsValid = false;
            }
        }

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

    /* Return result: */
    return fIsValid;
}
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();
                }
            }
        }
    }
}
Ejemplo n.º 29
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;
}
Ejemplo n.º 30
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;
}