Example #1
0
void Client::installColormap()
{
    Client *cc = 0;
    int i, found;

    if (m_colormapWinCount != 0) {

	found = 0;

	for (i = m_colormapWinCount - 1; i >= 0; --i) {
	    windowManager()->installColormap(m_windowColormaps[i]);
	    if (m_colormapWindows[i] == m_window) ++found;
	}

	if (found == 0) {
	    windowManager()->installColormap(m_colormap);
	}

    } else if (m_transient != None &&
	       (cc = windowManager()->windowToClient(m_transient))) {

	cc->installColormap();
    } else {
	windowManager()->installColormap(m_colormap);
    }
}
Example #2
0
void Client::hide()
{
    if (isHidden()) {
	fprintf(stderr, "wm2: Client already hidden in Client::hide\n");
	return;
    }

    m_border->unmap();
    XUnmapWindow(display(), m_window);

//    if (isActive()) windowManager()->setActiveClient(0);
    if (isActive()) windowManager()->clearFocus();

    setState(IconicState);
    windowManager()->addToHiddenList(this);
}
Example #3
0
u32 cForm::doModal()
{
    windowManager().addWindow( this );
    show();

    do { // manually update system loop
        timer().updateFps();
        INPUT & inputs = updateInput();
        processInput( inputs );
        windowManager().update();
        gdi().present( GE_MAIN );
        //dbg_printf( "modal window looping\n" );
    } while( modalRet() == (u32 )-1 );

    windowManager().removeWindow( this );
    return modalRet();
}
Example #4
0
void Client::activate()
{
//    fprintf(stderr, "Client::activate (this = %p, window = %x, parent = %x)\n",
//	    this, m_window, parent());

    if (parent() == root()) {
	fprintf(stderr, "wm2: warning: bad parent in Client::activate\n");
	return;
    }

    if (!m_managed || isHidden() || isWithdrawn()) return;

    if (isActive()) {
	decorate(True);
	if (CONFIG_AUTO_RAISE || CONFIG_RAISE_ON_FOCUS) mapRaised();
	return;
    }

    if (activeClient()) {
	activeClient()->deactivate();
	// & some other-screen business
    }

    XUngrabButton(display(), AnyButton, AnyModifier, parent());

    XSetInputFocus(display(), m_window, RevertToPointerRoot,
		   windowManager()->timestamp(False));

    if (m_protocol & PtakeFocus) {
	sendMessage(Atoms::wm_protocols, Atoms::wm_takeFocus);
    }

    // now set revert of window that reverts to this one so as to
    // revert to the window this one used to revert to (huh?)

    windowManager()->skipInRevert(this, m_revert);

    m_revert = activeClient();
    while (m_revert && !m_revert->isNormal()) m_revert = m_revert->revertTo();

    windowManager()->setActiveClient(this);
//    if (CONFIG_AUTO_RAISE || CONFIG_RAISE_ON_FOCUS) mapRaised();
    decorate(True);

    installColormap();		// new!
}
void UIMachineSettingsGeneral::putToCache()
{
    /* Prepare general data: */
    UIDataSettingsMachineGeneral generalData = m_cache.base();

    /* 'Basic' tab data: */
    AssertPtrReturnVoid(m_pNameAndSystemEditor);
    generalData.m_strName = m_pNameAndSystemEditor->name();
    generalData.m_strGuestOsTypeId = m_pNameAndSystemEditor->type().GetId();

    /* 'Advanced' tab data: */
    AssertPtrReturnVoid(mPsSnapshot);
    AssertPtrReturnVoid(mCbClipboard);
    AssertPtrReturnVoid(mCbDragAndDrop);
    generalData.m_strSnapshotsFolder = mPsSnapshot->path();
    generalData.m_clipboardMode = (KClipboardMode)mCbClipboard->currentIndex();
    generalData.m_dndMode = (KDnDMode)mCbDragAndDrop->currentIndex();

    /* 'Description' tab data: */
    AssertPtrReturnVoid(mTeDescription);
    generalData.m_strDescription = mTeDescription->toPlainText().isEmpty() ?
                                   QString::null : mTeDescription->toPlainText();

    /* 'Encryption' tab data: */
    AssertPtrReturnVoid(m_pCheckBoxEncryption);
    AssertPtrReturnVoid(m_pComboCipher);
    AssertPtrReturnVoid(m_pEditorEncryptionPassword);
    generalData.m_fEncryptionEnabled = m_pCheckBoxEncryption->isChecked();
    generalData.m_fEncryptionCipherChanged = m_fEncryptionCipherChanged;
    generalData.m_fEncryptionPasswordChanged = m_fEncryptionPasswordChanged;
    generalData.m_iEncryptionCipherIndex = m_pComboCipher->currentIndex();
    generalData.m_strEncryptionPassword = m_pEditorEncryptionPassword->text();
    /* If encryption status, cipher or password is changed: */
    if (generalData.m_fEncryptionEnabled != m_cache.base().m_fEncryptionEnabled ||
        generalData.m_fEncryptionCipherChanged != m_cache.base().m_fEncryptionCipherChanged ||
        generalData.m_fEncryptionPasswordChanged != m_cache.base().m_fEncryptionPasswordChanged)
    {
        /* Ask for the disk encryption passwords if necessary: */
        if (!m_cache.base().m_encryptedMediums.isEmpty())
        {
            /* Create corresponding dialog: */
            QWidget *pDlgParent = windowManager().realParentWindow(window());
            QPointer<UIAddDiskEncryptionPasswordDialog> pDlg =
                 new UIAddDiskEncryptionPasswordDialog(pDlgParent,
                                                       generalData.m_strName,
                                                       generalData.m_encryptedMediums);
            /* Execute it and acquire the result: */
            if (pDlg->exec() == QDialog::Accepted)
                generalData.m_encryptionPasswords = pDlg->encryptionPasswords();
            /* Delete dialog if still valid: */
            if (pDlg)
                delete pDlg;
        }
    }

    /* Cache general data: */
    m_cache.cacheCurrentData(generalData);
}
Example #6
0
bool cForm::processKeyMessage( const cKeyMessage & msg )
{
    bool ret = false;
    if( msg.id() == cMessage::keyDown ) {

        if( msg.keyCode() >=5 && msg.keyCode() <= 8 ) {

        std::list< cWindow * >::iterator it = _childWindows.begin();
        for( it = _childWindows.begin(); it != _childWindows.end(); ++it)
        {
            cWindow * window = *it;
            if( window->isFocused() ) {
                if( msg.keyCode() == cKeyMessage::UI_KEY_DOWN || msg.keyCode() == cKeyMessage::UI_KEY_RIGHT ) {
                    ++it;
                    if( it == _childWindows.end() )
                        it = _childWindows.begin();
                    if( (*it)->isVisible() ) {
                        windowManager().setFocusedWindow( (*it) );
                        ret = true;
                        break;
                    }
                } else if( msg.keyCode() == cKeyMessage::UI_KEY_UP || msg.keyCode() == cKeyMessage::UI_KEY_LEFT ) {
                    if( it == _childWindows.begin() ){
                        it = _childWindows.end();
                    }
                    --it;
                    if( (*it)->isVisible() ) {
                        windowManager().setFocusedWindow( (*it) );
                        ret = true;
                        break;
                    }
                }
            }
        }
        if( _childWindows.end() == it ) {
            if( _childWindows.front()->isVisible() ) {
                windowManager().setFocusedWindow( _childWindows.front() );
                ret = true;
            }
        }
        }
    }
    return ret;
}
Example #7
0
void Client::release()
{
    // assume wm called for this, and will remove me from its list itself

//    fprintf(stderr, "deleting client %p\n",this);

    if (m_window == None) {
	fprintf(stderr,
		"wm2: invalid parent in Client::release (released twice?)\n");
    }

    windowManager()->skipInRevert(this, m_revert);

//    fprintf(stderr, "deleting %lx\n",m_window);

    if (isHidden()) unhide(False);

    delete m_border;
    m_window = None;

    if (isActive()) {
	if (CONFIG_CLICK_TO_FOCUS) {
	    if (m_revert) {
		windowManager()->setActiveClient(m_revert);
		m_revert->activate();
	    } else windowManager()->setActiveClient(0);// windowManager()->clearFocus();
	} else {
	    windowManager()->setActiveClient(0);
	}
    }

    if (m_colormapWinCount > 0) {
	XFree((char *)m_colormapWindows);
	free((char *)m_windowColormaps); // not allocated through X
    }

    if (m_iconName) XFree(m_iconName);
    if (m_name)     XFree(m_name);
    if (m_label) free((void *)m_label);

    delete this;
}
void UINetworkManagerDialog::showEvent(QShowEvent *pShowEvent)
{
    /* Resize to minimum size-hint: */
    resize(minimumSizeHint());

    /* Center according current main application window: */
    vboxGlobal().centerWidget(this, windowManager().mainWindowShown(), false);

    /* Pass event to the base-class: */
    QMainWindow::showEvent(pShowEvent);
}
Example #9
0
void UIDownloaderExtensionPack::handleDownloadedObject(UINetworkReply *pReply)
{
    /* Read received data into the buffer: */
    QByteArray receivedData(pReply->readAll());
    /* Serialize that buffer into the file: */
    while (true)
    {
        /* Try to open file for writing: */
        QFile file(target());
        if (file.open(QIODevice::WriteOnly))
        {
            /* Write buffer into the file: */
            file.write(receivedData);
            file.close();

            /* Calc the SHA-256 on the bytes, creating a string: */
            uint8_t abHash[RTSHA256_HASH_SIZE];
            RTSha256(receivedData.constData(), receivedData.length(), abHash);
            char szDigest[RTSHA256_DIGEST_LEN + 1];
            int rc = RTSha256ToString(abHash, szDigest, sizeof(szDigest));
            if (RT_FAILURE(rc))
            {
                AssertRC(rc);
                szDigest[0] = '\0';
            }

            /* Warn the listener about extension-pack was downloaded: */
            emit sigDownloadFinished(source().toString(), target(), &szDigest[0]);
            break;
        }

        /* Warn the user about extension-pack was downloaded but was NOT saved: */
        msgCenter().cannotSaveExtensionPack(GUI_ExtPackName, source().toString(), QDir::toNativeSeparators(target()));

        /* Ask the user for another location for the extension-pack file: */
        QString strTarget = QIFileDialog::getExistingDirectory(QFileInfo(target()).absolutePath(),
                                                               windowManager().networkManagerOrMainWindowShown(),
                                                               tr("Select folder to save %1 to").arg(GUI_ExtPackName), true);

        /* Check if user had really set a new target: */
        if (!strTarget.isNull())
            setTarget(QDir(strTarget).absoluteFilePath(QFileInfo(target()).fileName()));
        else
            break;
    }
}
Example #10
0
void Client::unhide(Boolean map)
{
    if (!isHidden()) {
	fprintf(stderr, "wm2: Client not hidden in Client::unhide\n");
	return;
    }

    windowManager()->removeFromHiddenList(this);

    if (map) {
	setState(NormalState);
	XMapWindow(display(), m_window);
	mapRaised();

	if (CONFIG_AUTO_RAISE) focusIfAppropriate(False);
	else if (CONFIG_CLICK_TO_FOCUS) activate();
    }
}
Example #11
0
void Client::getTransient()
{
    Window t = None;

    if (XGetTransientForHint(display(), m_window, &t) != 0) {

	if (windowManager()->windowToClient(t) == this) {
	    fprintf(stderr,
		    "wm2: warning: client \"%s\" thinks it's a transient "
		    "for\nitself -- ignoring WM_TRANSIENT_FOR property...\n",
		    m_label ? m_label : "(no name)");
	    m_transient = None;
	} else {		
	    m_transient = t;
	}
    } else {
	m_transient = None;
    }
}
Example #12
0
void Client::sendMessage(Atom a, long l)
{
    XEvent ev;
    int status;
    long mask;

    memset(&ev, 0, sizeof(ev));
    ev.xclient.type = ClientMessage;
    ev.xclient.window = m_window;
    ev.xclient.message_type = a;
    ev.xclient.format = 32;
    ev.xclient.data.l[0] = l;
    ev.xclient.data.l[1] = windowManager()->timestamp(False);
    mask = 0L;
    status = XSendEvent(display(), m_window, False, mask, &ev);

    if (status == 0) {
	fprintf(stderr, "wm2: warning: Client::sendMessage failed\n");
    }
}
Example #13
0
        virtual void run()
        {
            QString result;

            QWidget *topParent = windowManager().realParentWindow(mParent ? mParent : windowManager().mainWindowShown());
            QString title = mCaption.isNull() ? tr ("Select a directory") : mCaption;

            TCHAR path [MAX_PATH];
            path [0] = 0;
            TCHAR initPath [MAX_PATH];
            initPath [0] = 0;

            BROWSEINFO bi;
            bi.hwndOwner = topParent ? topParent->winId() : 0;
            bi.pidlRoot = 0;
            bi.lpszTitle = (TCHAR*)(title.isNull() ? 0 : title.utf16());
            bi.pszDisplayName = initPath;
            bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
            bi.lpfn = winGetExistDirCallbackProc;
            bi.lParam = uintptr_t(&mDir);

            LPITEMIDLIST itemIdList = SHBrowseForFolder (&bi);
            if (itemIdList)
            {
                SHGetPathFromIDList (itemIdList, path);
                IMalloc *pMalloc;
                if (SHGetMalloc (&pMalloc) != NOERROR)
                    result = QString::null;
                else
                {
                    pMalloc->Free (itemIdList);
                    pMalloc->Release();
                    result = QString::fromUtf16 ((ushort*)path);
                }
            }
            else
                result = QString::null;
            QApplication::postEvent (mTarget, new GetExistDirectoryEvent (result));
        }
Example #14
0
void UIDownloaderUserManual::handleDownloadedObject(UINetworkReply *pReply)
{
    /* Read received data into the buffer: */
    QByteArray receivedData(pReply->readAll());
    /* Serialize that buffer into the file: */
    while (true)
    {
        /* Try to open file for writing: */
        QFile file(target());
        if (file.open(QIODevice::WriteOnly))
        {
            /* Write buffer into the file: */
            file.write(receivedData);
            file.close();

            /* Warn the user about user-manual loaded and saved: */
            msgCenter().warnAboutUserManualDownloaded(source().toString(), QDir::toNativeSeparators(target()));
            /* Warn the listener about user-manual was downloaded: */
            emit sigDownloadFinished(target());
            break;
        }

        /* Warn user about user-manual was downloaded but was NOT saved: */
        msgCenter().cannotSaveUserManual(source().toString(), QDir::toNativeSeparators(target()));

        /* Ask the user for another location for the user-manual file: */
        QString strTarget = QIFileDialog::getExistingDirectory(QFileInfo(target()).absolutePath(),
                                                               windowManager().networkManagerOrMainWindowShown(),
                                                               tr("Select folder to save User Manual to"), true);

        /* Check if user had really set a new target: */
        if (!strTarget.isNull())
            setTarget(QDir(strTarget).absoluteFilePath(QFileInfo(target()).fileName()));
        else
            break;
    }
}
void UIMachineWindow::closeEvent(QCloseEvent *pEvent)
{
    /* Always ignore close-event first: */
    pEvent->ignore();

    /* Make sure machine is in one of the allowed states: */
    if (!uisession()->isRunning() && !uisession()->isPaused() && !uisession()->isStuck())
        return;

    /* Get machine: */
    CMachine m = machine();

    /* If there is a close hook script defined: */
    QString strScript = m.GetExtraData(GUI_CloseActionHook);
    if (!strScript.isEmpty())
    {
        /* Execute asynchronously and leave: */
        QProcess::startDetached(strScript, QStringList() << m.GetId());
        return;
    }

    /* Choose the close action: */
    MachineCloseAction closeAction = MachineCloseAction_Invalid;

    /* If default close-action defined and not restricted: */
    MachineCloseAction defaultCloseAction = uisession()->defaultCloseAction();
    MachineCloseAction restrictedCloseActions = uisession()->restrictedCloseActions();
    if ((defaultCloseAction != MachineCloseAction_Invalid) &&
        !(restrictedCloseActions & defaultCloseAction))
    {
        switch (defaultCloseAction)
        {
            /* If VM is stuck, and the default close-action is 'save-state' or 'shutdown',
             * we should ask the user about what to do: */
            case MachineCloseAction_SaveState:
            case MachineCloseAction_Shutdown:
                closeAction = uisession()->isStuck() ? MachineCloseAction_Invalid : defaultCloseAction;
                break;
            /* Otherwise we just use what we have: */
            default:
                closeAction = defaultCloseAction;
                break;
        }
    }

    /* If the close-action still undefined: */
    if (closeAction == MachineCloseAction_Invalid)
    {
        /* Prepare close-dialog: */
        QWidget *pParentDlg = windowManager().realParentWindow(this);
        QPointer<UIVMCloseDialog> pCloseDlg = new UIVMCloseDialog(pParentDlg, m,
                                                                  session().GetConsole().GetGuestEnteredACPIMode(),
                                                                  restrictedCloseActions);

        /* Make sure close-dialog is valid: */
        if (pCloseDlg->isValid())
        {
            /* If VM is not paused and not stuck, we should pause it first: */
            bool fWasPaused = uisession()->isPaused() || uisession()->isStuck();
            if (fWasPaused || uisession()->pause())
            {
                /* Show close-dialog to let the user make the choice: */
                windowManager().registerNewParent(pCloseDlg, pParentDlg);
                closeAction = static_cast<MachineCloseAction>(pCloseDlg->exec());

                /* Make sure the dialog still valid: */
                if (!pCloseDlg)
                    return;

                /* If VM was not paused before but paused now,
                 * we should resume it if user canceled dialog or chosen shutdown: */
                if (!fWasPaused && uisession()->isPaused() &&
                    (closeAction == MachineCloseAction_Invalid ||
                     closeAction == MachineCloseAction_Shutdown))
                {
                    /* If we unable to resume VM, cancel closing: */
                    if (!uisession()->unpause())
                        closeAction = MachineCloseAction_Invalid;
                }
            }
        }
        else
        {
            /* Else user misconfigured .vbox file, we will reject closing UI: */
            closeAction = MachineCloseAction_Invalid;
        }

        /* Cleanup close-dialog: */
        delete pCloseDlg;
    }

    /* Depending on chosen result: */
    switch (closeAction)
    {
        case MachineCloseAction_SaveState:
        {
            /* Save VM state: */
            machineLogic()->saveState();
            break;
        }
        case MachineCloseAction_Shutdown:
        {
            /* Shutdown VM: */
            machineLogic()->shutdown();
            break;
        }
        case MachineCloseAction_PowerOff:
        case MachineCloseAction_PowerOff_RestoringSnapshot:
        {
            /* Power VM off: */
            machineLogic()->powerOff(closeAction == MachineCloseAction_PowerOff_RestoringSnapshot);
            break;
        }
        default:
            break;
    }
}
Example #16
0
void UIMachineWindow::closeEvent(QCloseEvent *pCloseEvent)
{
    /* Always ignore close-event first: */
    pCloseEvent->ignore();

    /* Make sure machine is in one of the allowed states: */
    if (!uisession()->isRunning() && !uisession()->isPaused() && !uisession()->isStuck())
        return;

    /* If there is a close hook script defined: */
    const QString strScript = gEDataManager->machineCloseHookScript(vboxGlobal().managedVMUuid());
    if (!strScript.isEmpty())
    {
        /* Execute asynchronously and leave: */
        QProcess::startDetached(strScript, QStringList() << machine().GetId());
        return;
    }

    /* Choose the close action: */
    MachineCloseAction closeAction = MachineCloseAction_Invalid;

    /* If default close-action defined and not restricted: */
    MachineCloseAction defaultCloseAction = uisession()->defaultCloseAction();
    MachineCloseAction restrictedCloseActions = uisession()->restrictedCloseActions();
    if ((defaultCloseAction != MachineCloseAction_Invalid) &&
        !(restrictedCloseActions & defaultCloseAction))
    {
        switch (defaultCloseAction)
        {
            /* If VM is stuck, and the default close-action is 'detach', 'save-state' or 'shutdown',
             * we should ask the user about what to do: */
            case MachineCloseAction_Detach:
            case MachineCloseAction_SaveState:
            case MachineCloseAction_Shutdown:
                closeAction = uisession()->isStuck() ? MachineCloseAction_Invalid : defaultCloseAction;
                break;
            /* Otherwise we just use what we have: */
            default:
                closeAction = defaultCloseAction;
                break;
        }
    }

    /* If the close-action still undefined: */
    if (closeAction == MachineCloseAction_Invalid)
    {
        /* Prepare close-dialog: */
        QWidget *pParentDlg = windowManager().realParentWindow(this);
        QPointer<UIVMCloseDialog> pCloseDlg = new UIVMCloseDialog(pParentDlg, machine(),
                                                                  console().GetGuestEnteredACPIMode(),
                                                                  restrictedCloseActions);

        /* Make sure close-dialog is valid: */
        if (pCloseDlg->isValid())
        {
            /* We are going to show close-dialog: */
            bool fShowCloseDialog = true;
            /* Check if VM is paused or stuck: */
            const bool fWasPaused = uisession()->isPaused();
            const bool fIsStuck = uisession()->isStuck();
            /* If VM is NOT paused and NOT stuck: */
            if (!fWasPaused && !fIsStuck)
            {
                /* We should pause it first: */
                const bool fIsPaused = uisession()->pause();
                /* If we were unable to pause VM: */
                if (!fIsPaused)
                {
                    /* If that is NOT the separate VM process UI: */
                    if (!vboxGlobal().isSeparateProcess())
                    {
                        /* We are not going to show close-dialog: */
                        fShowCloseDialog = false;
                    }
                    /* If that is the separate VM process UI: */
                    else
                    {
                        /* We are going to show close-dialog only
                         * if headless frontend stopped/killed already: */
                        CMachine machine = uisession()->machine();
                        KMachineState machineState = machine.GetState();
                        fShowCloseDialog = !machine.isOk() || machineState == KMachineState_Null;
                    }
                }
            }
            /* If we are going to show close-dialog: */
            if (fShowCloseDialog)
            {
                /* Show close-dialog to let the user make the choice: */
                windowManager().registerNewParent(pCloseDlg, pParentDlg);
                closeAction = static_cast<MachineCloseAction>(pCloseDlg->exec());

                /* Make sure the dialog still valid: */
                if (!pCloseDlg)
                    return;

                /* If VM was not paused before but paused now,
                 * we should resume it if user canceled dialog or chosen shutdown: */
                if (!fWasPaused && uisession()->isPaused() &&
                    (closeAction == MachineCloseAction_Invalid ||
                     closeAction == MachineCloseAction_Detach ||
                     closeAction == MachineCloseAction_Shutdown))
                {
                    /* If we unable to resume VM, cancel closing: */
                    if (!uisession()->unpause())
                        closeAction = MachineCloseAction_Invalid;
                }
            }
        }
        else
        {
            /* Else user misconfigured .vbox file, we will reject closing UI: */
            closeAction = MachineCloseAction_Invalid;
        }

        /* Cleanup close-dialog: */
        delete pCloseDlg;
    }

    /* Depending on chosen result: */
    switch (closeAction)
    {
        case MachineCloseAction_Detach:
        {
            /* Just close Runtime UI: */
            LogRel(("GUI: Request for close-action to detach GUI.\n"));
            machineLogic()->detach();
            break;
        }
        case MachineCloseAction_SaveState:
        {
            /* Save VM state: */
            LogRel(("GUI: Request for close-action to save VM state.\n"));
            machineLogic()->saveState();
            break;
        }
        case MachineCloseAction_Shutdown:
        {
            /* Shutdown VM: */
            LogRel(("GUI: Request for close-action to shutdown VM.\n"));
            machineLogic()->shutdown();
            break;
        }
        case MachineCloseAction_PowerOff:
        case MachineCloseAction_PowerOff_RestoringSnapshot:
        {
            /* Power VM off: */
            LogRel(("GUI: Request for close-action to power VM off.\n"));
            machineLogic()->powerOff(closeAction == MachineCloseAction_PowerOff_RestoringSnapshot);
            break;
        }
        default:
            break;
    }
}
Example #17
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 UIMachineWindow::closeEvent(QCloseEvent *pEvent)
{
    /* Always ignore close-event first: */
    pEvent->ignore();

    /* Make sure machine is in one of the allowed states: */
    if (!uisession()->isRunning() && !uisession()->isPaused() && !uisession()->isStuck())
        return;

    /* If there is a close hook script defined: */
    QString strScript = machine().GetExtraData(GUI_CloseActionHook);
    if (!strScript.isEmpty())
    {
        /* Execute asynchronously and leave: */
        QProcess::startDetached(strScript, QStringList() << machine().GetId());
        return;
    }

    /* Choose the close action: */
    MachineCloseAction closeAction = MachineCloseAction_Invalid;

    /* If there IS default close-action defined: */
    QString strDefaultAction = machine().GetExtraData(GUI_DefaultCloseAction);
    if (!strDefaultAction.isEmpty())
    {
        /* Parse the close-action which was defined: */
        closeAction = gpConverter->fromInternalString<MachineCloseAction>(strDefaultAction);
        /* If VM is stuck, and the default close-action is not 'power-off',
         * we should ask the user about what to do: */
        if (uisession()->isStuck() &&
            closeAction != MachineCloseAction_PowerOff)
            closeAction = MachineCloseAction_Invalid;
        /* If the default-action is 'power-off',
         * we should check if its possible to discard machine-state: */
        if (closeAction == MachineCloseAction_PowerOff &&
            machine().GetSnapshotCount() > 0)
            closeAction = MachineCloseAction_PowerOff_RestoringSnapshot;
    }

    /* If the close-action still undefined: */
    if (closeAction == MachineCloseAction_Invalid)
    {
        /* Prepare close-dialog: */
        QWidget *pParentDlg = windowManager().realParentWindow(this);
        QPointer<UIVMCloseDialog> pCloseDlg = new UIVMCloseDialog(pParentDlg, machine(), session());

        /* Make sure close-dialog is valid: */
        if (pCloseDlg->isValid())
        {
            /* If VM is not paused and not stuck, we should pause it first: */
            bool fWasPaused = uisession()->isPaused() || uisession()->isStuck();
            if (fWasPaused || uisession()->pause())
            {
                /* Show close-dialog to let the user make the choice: */
                windowManager().registerNewParent(pCloseDlg, pParentDlg);
                closeAction = static_cast<MachineCloseAction>(pCloseDlg->exec());

                /* Make sure the dialog still valid: */
                if (!pCloseDlg)
                    return;

                /* If VM was not paused before but paused now,
                 * we should resume it if user canceled dialog or chosen shutdown: */
                if (!fWasPaused && uisession()->isPaused() &&
                    (closeAction == MachineCloseAction_Invalid ||
                     closeAction == MachineCloseAction_Shutdown))
                {
                    /* If we unable to resume VM, cancel closing: */
                    if (!uisession()->unpause())
                        closeAction = MachineCloseAction_Invalid;
                }
            }
        }
        else
        {
            /* Else user misconfigured .vbox file, 'power-off' will be the action: */
            closeAction = MachineCloseAction_PowerOff;
        }

        /* Cleanup close-dialog: */
        delete pCloseDlg;
    }

    /* Depending on chosen result: */
    switch (closeAction)
    {
        case MachineCloseAction_SaveState:
        {
            /* Save VM state: */
            machineLogic()->saveState();
            break;
        }
        case MachineCloseAction_Shutdown:
        {
            /* Shutdown VM: */
            machineLogic()->shutdown();
            break;
        }
        case MachineCloseAction_PowerOff:
        case MachineCloseAction_PowerOff_RestoringSnapshot:
        {
            /* Power VM off: */
            machineLogic()->powerOff(closeAction == MachineCloseAction_PowerOff_RestoringSnapshot);
            break;
        }
        default:
            break;
    }
}
Example #19
0
        virtual void run()
        {
            QString result;

            QString workDir;
            QString initSel;
            QFileInfo fi (mStartWith);

            if (fi.isDir())
                workDir = mStartWith;
            else
            {
                workDir = fi.absolutePath();
                initSel = fi.fileName();
            }

            workDir = QDir::toNativeSeparators (workDir);
            if (!workDir.endsWith ("\\"))
                workDir += "\\";

            QString title = mCaption.isNull() ? tr ("Select a file") : mCaption;

            QWidget *topParent = windowManager().realParentWindow(mParent ? mParent : windowManager().mainWindowShown());
            QString winFilters = winFilter (mFilters);
            AssertCompile (sizeof (TCHAR) == sizeof (QChar));
            TCHAR buf [1024];
            if (initSel.length() > 0 && initSel.length() < sizeof (buf))
                memcpy (buf, initSel.isNull() ? 0 : initSel.utf16(),
                        (initSel.length() + 1) * sizeof (TCHAR));
            else
                buf [0] = 0;

            OPENFILENAME ofn;
            memset (&ofn, 0, sizeof (OPENFILENAME));

            ofn.lStructSize = sizeof (OPENFILENAME);
            ofn.hwndOwner = topParent ? topParent->winId() : 0;
            ofn.lpstrFilter = (TCHAR *)(winFilters.isNull() ? 0 : winFilters.utf16());
            ofn.lpstrFile = buf;
            ofn.nMaxFile = sizeof (buf) - 1;
            ofn.lpstrInitialDir = (TCHAR *)(workDir.isNull() ? 0 : workDir.utf16());
            ofn.lpstrTitle = (TCHAR *)(title.isNull() ? 0 : title.utf16());
            ofn.Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY |
                          OFN_EXPLORER | OFN_ENABLEHOOK |
                          OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST);
            ofn.lpfnHook = OFNHookProc;

            if (GetOpenFileName (&ofn))
            {
                result = QString::fromUtf16 ((ushort *) ofn.lpstrFile);
            }

            // qt_win_eatMouseMove();
            MSG msg = {0, 0, 0, 0, 0, 0, 0};
            while (PeekMessage (&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
            if (msg.message == WM_MOUSEMOVE)
                PostMessage (msg.hwnd, msg.message, 0, msg.lParam);

            result = result.isEmpty() ? result : QFileInfo (result).absoluteFilePath();

            QApplication::postEvent (mTarget, new GetOpenFileNameEvent (result));
        }
Example #20
0
void UIProgressDialog::timerEvent(QTimerEvent* /* pEvent */)
{
    /* We should hide progress-dialog
     * if it was already finalized but not yet closed.
     * This could happens in case of some other
     * modal dialog prevents our event-loop from
     * being exit overlapping 'this'. */
    if (m_fEnded && !isHidden() && windowManager().isWindowOnTheTopOfTheModalWindowStack(this))
    {
        hide();
        return;
    }
    else if (m_fEnded)
        return;

    if (!m_fEnded && (!m_progress.isOk() || m_progress.GetCompleted()))
    {
        /* Is this progress-dialog a top-level modal-dialog now? */
        if (windowManager().isWindowOnTheTopOfTheModalWindowStack(this))
        {
            /* Progress finished: */
            if (m_progress.isOk())
            {
                m_pProgressBar->setValue(100);
                done(Accepted);
            }
            /* Progress is not valid: */
            else
                done(Rejected);

            /* Request to exit loop: */
            m_fEnded = true;
            return;
        }
        /* Else we should wait until all the subsequent
         * top-level modal-dialog(s) will be dismissed: */
        return;
    }

    if (!m_progress.GetCanceled())
    {
        /* Update the progress dialog: */
        /* First ETA */
        long newTime = m_progress.GetTimeRemaining();
        long seconds;
        long minutes;
        long hours;
        long days;

        seconds  = newTime < 0 ? 0 : newTime;
        minutes  = seconds / 60;
        seconds -= minutes * 60;
        hours    = minutes / 60;
        minutes -= hours   * 60;
        days     = hours   / 24;
        hours   -= days    * 24;

        QString strDays = VBoxGlobal::daysToString(days);
        QString strHours = VBoxGlobal::hoursToString(hours);
        QString strMinutes = VBoxGlobal::minutesToString(minutes);
        QString strSeconds = VBoxGlobal::secondsToString(seconds);

        QString strTwoComp = tr("%1, %2 remaining", "You may wish to translate this more like \"Time remaining: %1, %2\"");
        QString strOneComp = tr("%1 remaining", "You may wish to translate this more like \"Time remaining: %1\"");

        if      (days > 1 && hours > 0)
            m_pEtaLbl->setText(strTwoComp.arg(strDays).arg(strHours));
        else if (days > 1)
            m_pEtaLbl->setText(strOneComp.arg(strDays));
        else if (days > 0 && hours > 0)
            m_pEtaLbl->setText(strTwoComp.arg(strDays).arg(strHours));
        else if (days > 0 && minutes > 5)
            m_pEtaLbl->setText(strTwoComp.arg(strDays).arg(strMinutes));
        else if (days > 0)
            m_pEtaLbl->setText(strOneComp.arg(strDays));
        else if (hours > 2)
            m_pEtaLbl->setText(strOneComp.arg(strHours));
        else if (hours > 0 && minutes > 0)
            m_pEtaLbl->setText(strTwoComp.arg(strHours).arg(strMinutes));
        else if (hours > 0)
            m_pEtaLbl->setText(strOneComp.arg(strHours));
        else if (minutes > 2)
            m_pEtaLbl->setText(strOneComp.arg(strMinutes));
        else if (minutes > 0 && seconds > 5)
            m_pEtaLbl->setText(strTwoComp.arg(strMinutes).arg(strSeconds));
        else if (minutes > 0)
            m_pEtaLbl->setText(strOneComp.arg(strMinutes));
        else if (seconds > 5)
            m_pEtaLbl->setText(strOneComp.arg(strSeconds));
        else if (seconds > 0)
            m_pEtaLbl->setText(tr("A few seconds remaining"));
        else
            m_pEtaLbl->clear();

        /* Then operation text if changed: */
        ulong newOp = m_progress.GetOperation() + 1;
        if (newOp != m_iCurrentOperation)
        {
            m_iCurrentOperation = newOp;
            m_pDescriptionLbl->setText(QString(m_spcszOpDescTpl)
                                       .arg(m_progress.GetOperationDescription())
                                       .arg(m_iCurrentOperation).arg(m_cOperations));
        }
        m_pProgressBar->setValue(m_progress.GetPercent());

        /* Then cancel button: */
        m_fCancelEnabled = m_progress.GetCancelable();
        m_pCancelBtn->setEnabled(m_fCancelEnabled);
    }
    else
        m_pEtaLbl->setText(m_strCancel);
}
Example #21
0
void Client::mapRaised()
{
    m_border->mapRaised();
    windowManager()->raiseTransients(this);
}