Esempio n. 1
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();
}
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);
}
Esempio n. 3
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);
}
Esempio n. 4
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;
}
Esempio n. 5
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();
}
Esempio n. 6
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;
}
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);
                    }
                }
            }
        }
Esempio n. 8
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 (m_dndSource.isOk())
                {
                    if (vecData.isEmpty())
                        rc = VERR_NO_DATA;
                }
                else
                {
                    msgCenter().cannotDropDataToHost(m_dndSource, m_pParent);
                    rc = VERR_GENERAL_FAILURE; /** @todo Fudge; do a GetResultCode() to rc translation. */
                }
            }
            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. */
    }

    setOpMode(DNDMODE_UNKNOWN);

    LogFlowFuncLeaveRC(rc);
    return rc;
}
Esempio n. 9
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);
}
Esempio n. 10
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;
}
/**
 * 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;
}
Esempio n. 12
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;
}
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();
                }
            }
        }
    }
}
Esempio n. 14
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;
}
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;
}