Example #1
0
MainWindow* MainWindow::findMainWindow(QObject *parent)
{
	MainWindow *window = NULL;
	QWidget *widget = qobject_cast<QWidget*>(parent);

	if (widget && widget->window())
	{
		parent = widget->window();
	}

	while (parent)
	{
		if (parent->metaObject()->className() == QLatin1String("Otter::MainWindow"))
		{
			window = qobject_cast<MainWindow*>(parent);

			break;
		}

		parent = parent->parent();
	}

	if (!window)
	{
		window = qobject_cast<MainWindow*>(SessionsManager::getActiveWindow());
	}

	return window;
}
Example #2
0
/**
* @brief 获取最上层活动视窗
*/
QWidget *topLevelWidget()
{
    QWidget *parent = qApp->activeModalWidget();
    if (!parent)
        parent = qApp->activeWindow();
    if (parent && parent->window())
        parent = parent->window();
    return parent;
}
Example #3
0
void WinIntegration::updateAssocs()
{
	QWidget *window = dynamic_cast<QWidget*>(sender());
	if (window)
		window = window->window();
	ShellExecuteA(window->winId(), "runas", "wininthelper.exe", "assocreg", 0, 0);
}
Example #4
0
/*
  Internal function called from QWidget::setCursor()
   force is true if this function is called from dispatchEnterLeave, it means that the
   mouse is actually directly under this widget.
*/
void qt_symbian_set_cursor(QWidget *w, bool force)
{
    static QPointer<QWidget> lastUnderMouse = 0;
    if (force) {
        lastUnderMouse = w;
    }
    else if (w->testAttribute(Qt::WA_WState_Created) && lastUnderMouse
        && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
        w = lastUnderMouse;
    }

    if (!S60->curWin && w && w->internalWinId())
        return;
    QWidget* cW = w && !w->internalWinId() ? w : QWidget::find(S60->curWin);
    if (!cW || cW->window() != w->window() || !cW->isVisible() || !cW->underMouse()
        || QApplication::overrideCursor())
        return;

#ifndef Q_SYMBIAN_FIXED_POINTER_CURSORS
    if (S60->brokenPointerCursors)
        qt_symbian_set_pointer_sprite(cW->cursor());
    else
#endif
        qt_symbian_setWindowCursor(cW->cursor(), w->effectiveWinId());
}
Example #5
0
QWidget *QWidgetProto::window() const
{
  QWidget *item = qscriptvalue_cast<QWidget*>(thisObject());
  if (item)
    return item->window();
  return 0;
}
Example #6
0
/*!
    \property QStackedLayout::currentIndex
    \brief the index position of the widget that is visible

    The current index is -1 if there is no current widget.

    \sa currentWidget(), indexOf()
*/
void QStackedLayout::setCurrentIndex(int index)
{
    Q_D(QStackedLayout);
    QWidget *prev = currentWidget();
    QWidget *next = widget(index);
    if (!next || next == prev)
        return;

    bool reenableUpdates = false;
    QWidget *parent = parentWidget();

    if (parent && parent->updatesEnabled()) {
        reenableUpdates = true;
        parent->setUpdatesEnabled(false);
    }

    QPointer<QWidget> fw = parent ? parent->window()->focusWidget() : 0;
    const bool focusWasOnOldPage = fw && (prev && prev->isAncestorOf(fw));

    if (prev) {
        prev->clearFocus();
        if (d->stackingMode == StackOne)
            prev->hide();
    }

    d->index = index;
    next->raise();
    next->show();

    // try to move focus onto the incoming widget if focus
    // was somewhere on the outgoing widget.

    if (parent) {
        if (focusWasOnOldPage) {
            // look for the best focus widget we can find
            if (QWidget *nfw = next->focusWidget())
                nfw->setFocus();
            else {
                // second best: first child widget in the focus chain
                if (QWidget *i = fw) {
                    while ((i = i->nextInFocusChain()) != fw) {
                        if (((i->focusPolicy() & Qt::TabFocus) == Qt::TabFocus)
                            && !i->focusProxy() && i->isVisibleTo(next) && i->isEnabled()
                            && next->isAncestorOf(i)) {
                            i->setFocus();
                            break;
                        }
                    }
                    // third best: incoming widget
                    if (i == fw )
                        next->setFocus();
                }
            }
        }
    }
    if (reenableUpdates)
        parent->setUpdatesEnabled(true);
    emit currentChanged(index);
}
Example #7
0
/**
* @brief 提示信息显示窗口
* @param [I] 图标
* @param [I] 信息串
* @param [I] 按键
* @param [I] 缺省按键
*/
static QMessageBox::StandardButton showMessageBox(QMessageBox::Icon icon,
                                                  const QString &text,
                                                  QMessageBox::StandardButtons buttons,
                                                  QMessageBox::StandardButton defaultButton)
{
    WaitCursor arrow(Qt::ArrowCursor);

    QWidget *parent = qApp->activeModalWidget();
    if (!parent)
        parent = qApp->activeWindow();
    if (parent && parent->window())
        parent = parent->window();

    QMessageBox box(icon, qApp->applicationName(), text, buttons, parent);
    if (defaultButton != QMessageBox::NoButton)
        box.setDefaultButton(defaultButton);
    return (QMessageBox::StandardButton)box.exec();
}
Example #8
0
void ChromeClientQt::show()
{
    if (!m_webPage)
        return;
    QWidget* view = m_webPage->view();
    if (!view)
        return;
    view->window()->show();
}
Example #9
0
QString qt_win_CID_get_existing_directory(const QFileDialogArgs &args)
{
    QString result;
    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);

    IFileOpenDialog *pfd = 0;
    HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
                                  QT_IID_IFileOpenDialog, reinterpret_cast<void**>(&pfd));

    if (SUCCEEDED(hr)) {
        qt_win_set_IFileDialogOptions(pfd, args.selection,
                                      args.directory, args.caption,
                                      QStringList(), QFileDialog::ExistingFile,
                                      args.options);

        // Set the FOS_PICKFOLDERS flag
        DWORD newOptions;
        hr = pfd->GetOptions(&newOptions);
        newOptions |= (FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
        if (SUCCEEDED(hr) && SUCCEEDED((hr = pfd->SetOptions(newOptions)))) {
            QWidget *parentWindow = args.parent;
            if (parentWindow)
                parentWindow = parentWindow->window();
            else
                parentWindow = QApplication::activeWindow();

            // Show the file dialog.
            hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
            if (SUCCEEDED(hr)) {
                // Retrieve the result
                IShellItem *psi = 0;
                hr = pfd->GetResult(&psi);
                if (SUCCEEDED(hr)) {
                    // Retrieve the file name from shell item.
                    wchar_t *pszPath;
                    hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                    if (SUCCEEDED(hr)) {
                        result = QString::fromWCharArray(pszPath);
                        CoTaskMemFree(pszPath);
                    }
                    psi->Release(); // Free the current item.
                }
            }
        }
    }
    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (pfd)
        pfd->Release();
    return result;
}
Example #10
0
bool
BlurHelper::eventFilter(QObject *object, QEvent *event)
{
    // do nothing if not enabled
    if (!enabled())
        return false;
    switch (event->type()) {
    case QEvent::Hide: {
        QWidget *widget = qtcToWidget(object);
        if (widget && isOpaque(widget)) {
            QWidget *window(widget->window());
            if (window && isTransparent(window) &&
                    !_pendingWidgets.contains(window)) {
                _pendingWidgets.insert(window, window);
                delayedUpdate();
            }
        }
        break;
    }
    case QEvent::Show:
    case QEvent::Resize: {
        // cast to widget and check
        QWidget *widget = qtcToWidget(object);
        if (!widget)
            break;
        if (isTransparent(widget)) {
            _pendingWidgets.insert(widget, widget);
            delayedUpdate();
        } else if (isOpaque(widget)) {
            QWidget* window(widget->window());
            if (isTransparent(window)) {
                _pendingWidgets.insert(window, window);
                delayedUpdate();
            }
        }
        break;
    }
    default:
        break;
    }
    // never eat events
    return false;
}
Example #11
0
void QWSInputContext::update()
{
    QWidget *w = focusWidget();
    if (!w)
        return;

    QWidget *tlw = w->window();
    int winid = tlw->winId();

    int widgetid = w->winId();
    QPaintDevice::qwsDisplay()->sendIMUpdate(QWSInputMethod::Update, winid, widgetid);

}
Example #12
0
void QStyleAnimation::updateCurrentTime(int)
{
    if (QObject *tgt = target()) {
        if (tgt->isWidgetType()) {
            QWidget *widget = static_cast<QWidget *>(tgt);
            if (!widget->isVisible() || widget->window()->isMinimized())
                stop();
        }

        if (isUpdateNeeded())
            updateTarget();
    }
}
Example #13
0
void AccessManager::setCookieJarWindowId(WId id)
{
    QWidget* window = QWidget::find(id);
    if (!window) {
        return;
    }

    KIO::Integration::CookieJar *jar = qobject_cast<KIO::Integration::CookieJar *> (cookieJar());
    if (jar) {
        jar->setWindowId(id);
    }

    d->window = window->isWindow() ? window : window->window();
}
Example #14
0
/*
    \internal
    Returns the toplevel widget parent of this script, or
    the application' active window if there is no widget parent.
*/
QWidget *QAxScriptSite::window() const
{
    QWidget *w = 0;
    QObject *p = script->parent();
    while (!w && p) {
        w = qobject_cast<QWidget*>(p);
        p = p->parent();
    }
    
    if (w)
        w = w->window();
    if (!w && qApp)
        w = qApp->activeWindow();
    
    return w;
}
Example #15
0
QStyleOptionMenuItem KxMenuItemWidget::getStyleOption() const
{
    QWidget *q = parentWidget();
    QMenu *menu = (QMenu *)q;
    KxMenuItem *action = fMenuItem;
    QStyleOptionMenuItem opt;

    opt.initFrom(this);
    opt.palette = q->palette();
    opt.state = QStyle::State_None;

    if (q->window()->isActiveWindow())
        opt.state |= QStyle::State_Active;
    if (q->isEnabled() && action->isEnabled()
        && (!action->menu() || action->menu()->isEnabled()))
        opt.state |= QStyle::State_Enabled;
    else
        opt.palette.setCurrentColorGroup(QPalette::Disabled);

    opt.font = action->font();

    if (menu->activeAction() == action && !action->isSeparator()) {
        opt.state |= QStyle::State_Selected;
        // 					 | (mouseDown ? QStyle::State_Sunken : QStyle::State_None);
    }

    if (!action->isCheckable()) {
        opt.checkType = QStyleOptionMenuItem::NotCheckable;
    } else {
        opt.checkType = (action->actionGroup() && action->actionGroup()->isExclusive())
            ? QStyleOptionMenuItem::Exclusive : QStyleOptionMenuItem::NonExclusive;
        opt.checked = action->isChecked();
    }
    if (action->menu())
        opt.menuItemType = QStyleOptionMenuItem::SubMenu;
    else if (action->isSeparator())
        opt.menuItemType = QStyleOptionMenuItem::Separator;
    else if (menu->defaultAction() == action)
        opt.menuItemType = QStyleOptionMenuItem::DefaultItem;
    else
        opt.menuItemType = QStyleOptionMenuItem::Normal;
    opt.icon = action->icon();
    opt.text = action->text();
    opt.menuRect = q->rect();
    return opt;
}
Example #16
0
void Browser::showView(GalleryView *view, const QVariant &containerId, const QString &title)
{
    view->showChildren(containerId);

#ifdef Q_WS_MAEMO_5
    QWidget *parent = qobject_cast<QWidget *>(sender());
    if (parent)
        view->setParent(parent->window(), Qt::Window);
    view->setAttribute(Qt::WA_Maemo5StackedWindow);
    view->setAttribute(Qt::WA_DeleteOnClose);
    view->setWindowTitle(title);
    view->show();
#else
    stack->setCurrentWidget(view);

    setWindowTitle(title);
#endif
}
Example #17
0
int QPrintDialogPrivate::openWindowsPrintDialogModally()
{
    Q_Q(QPrintDialog);
    QWidget *parent = q->parentWidget();
    if (parent)
        parent = parent->window();
    else
        parent = qApp->activeWindow();

    QWidget modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);

    HGLOBAL *tempDevNames = ep->createDevNames();

    bool result;
    bool done;
    void *pd = QT_WA_INLINE(
        (void*)(qt_win_make_PRINTDLG<PRINTDLGW, DEVMODEW>(parent, q, this, tempDevNames)),
        (void*)(qt_win_make_PRINTDLG<PRINTDLGA, DEVMODEA>(parent, q, this, tempDevNames))
        );

    do {
        done = true;
        QT_WA({
            PRINTDLGW *pdw = reinterpret_cast<PRINTDLGW *>(pd);
            result = PrintDlgW(pdw);
            if ((pdw->Flags & PD_PAGENUMS) && (pdw->nFromPage > pdw->nToPage))
                done = false;
            if (result && pdw->hDC == 0)
                result = false;
            else if (!result)
                done = true;
        }, {
            PRINTDLGA *pda = reinterpret_cast<PRINTDLGA *>(pd);
            result = PrintDlgA(pda);
            if ((pda->Flags & PD_PAGENUMS) && (pda->nFromPage > pda->nToPage))
                done = false;
            if (result && pda->hDC == 0)
                result = false;
            else if (!result)
                done = true;
        });
Example #18
0
bool TabWidget::isActiveChatWindow()
{
  QWidget *widget = m_self->parentWidget();
  if (widget->isMinimized() || widget->isHidden())
    return false;

# if defined(Q_OS_WIN32)
  if (widget->isActiveWindow()) {
    HWND active = GetForegroundWindow();
    if (active == (HWND) widget->window()->internalWinId() || ::IsChild(active, (HWND) widget->window()->internalWinId()))
      return true;
    else
      return false;
  }
  else
    return false;
# else
  return widget->isActiveWindow();
# endif
}
bool UIMachineSettingsSystem::eventFilter(QObject *pObject, QEvent *pEvent)
{
    if (!pObject->isWidgetType())
        return QWidget::eventFilter(pObject, pEvent);

    QWidget *pWidget = static_cast<QWidget*>(pObject);
    if (pWidget->window() != window())
        return QWidget::eventFilter(pObject, pEvent);

    switch (pEvent->type())
    {
        case QEvent::FocusIn:
        {
            /* Boot Table: */
            if (pWidget == mTwBootOrder)
            {
                if (!mTwBootOrder->currentItem())
                    mTwBootOrder->setCurrentItem(mTwBootOrder->item(0));
                else
                    sltCurrentBootItemChanged(mTwBootOrder->currentRow());
                mTwBootOrder->currentItem()->setSelected(true);
            }
            else if (pWidget != mTbBootItemUp && pWidget != mTbBootItemDown)
            {
                if (mTwBootOrder->currentItem())
                {
                    mTwBootOrder->currentItem()->setSelected(false);
                    mTbBootItemUp->setEnabled(false);
                    mTbBootItemDown->setEnabled(false);
                }
            }
            break;
        }
        default:
            break;
    }

    return QWidget::eventFilter(pObject, pEvent);
}
Example #20
0
bool UISettingsDialog::eventFilter(QObject *pObject, QEvent *pEvent)
{
    /* Ignore objects which are NOT widgets: */
    if (!pObject->isWidgetType())
        return QIMainDialog::eventFilter(pObject, pEvent);

    /* Ignore widgets which window is NOT settings dialog: */
    QWidget *pWidget = static_cast<QWidget*>(pObject);
    if (pWidget->window() != this)
        return QIMainDialog::eventFilter(pObject, pEvent);

    /* Process different event-types: */
    switch (pEvent->type())
    {
        /* Process enter/leave events to remember whats-this candidates: */
        case QEvent::Enter:
        case QEvent::Leave:
        {
            if (pEvent->type() == QEvent::Enter)
                m_pWhatsThisCandidate = pWidget;
            else
                m_pWhatsThisCandidate = 0;

            m_pWhatsThisTimer->start(100);
            break;
        }
        /* Process focus-in event to update whats-this pane: */
        case QEvent::FocusIn:
        {
            sltUpdateWhatsThis(true /* got focus? */);
            break;
        }
        default:
            break;
    }

    /* Base-class processing: */
    return QIMainDialog::eventFilter(pObject, pEvent);
}
Example #21
0
void QWSInputContext::setFocusWidget( QWidget *w )
{
    QWidget *oldFocus = focusWidget();
    if (oldFocus == w)
        return;

    if (w) {
        QWSInputContext::updateImeStatus(w, true);
    } else {
        if (oldFocus)
            QWSInputContext::updateImeStatus(oldFocus, false);
    }

    if (oldFocus) {
        QWidget *tlw = oldFocus->window();
        int winid = tlw->internalWinId();

        int widgetid = oldFocus->internalWinId();
        QPaintDevice::qwsDisplay()->sendIMUpdate(QWSInputMethod::FocusOut, winid, widgetid);
    }

    QInputContext::setFocusWidget(w);

    if (!w)
        return;

    QWidget *tlw = w->window();
    int winid = tlw->winId();

    int widgetid = w->winId();
    QPaintDevice::qwsDisplay()->sendIMUpdate(QWSInputMethod::FocusIn, winid, widgetid);

    //setfocus ???

    update();
}
Example #22
0
IntRect ChromeClientQt::windowResizerRect() const
{
#if defined(Q_WS_MAC)
    if (!m_webPage)
        return IntRect();

    QWebPageClient* pageClient = platformPageClient();
    if (!pageClient)
        return IntRect();

    QWidget* ownerWidget = pageClient->ownerWidget();
    if (!ownerWidget)
        return IntRect();

    QWidget* topLevelWidget = ownerWidget->window();
    QRect topLevelGeometry(topLevelWidget->geometry());

    // There's no API in Qt to query for the size of the resizer, so we assume
    // it has the same width and height as the scrollbar thickness.
    int scollbarThickness = ScrollbarTheme::theme()->scrollbarThickness();

    // There's no API in Qt to query for the position of the resizer. Sometimes
    // it's drawn by the system, and sometimes it's a QSizeGrip. For RTL locales
    // it might even be on the lower left side of the window, but in WebKit we
    // always draw scrollbars on the right hand side, so we assume this to be the
    // location when computing the resize rect to reserve for WebKit.
    QPoint resizeCornerTopLeft = ownerWidget->mapFrom(topLevelWidget,
            QPoint(topLevelGeometry.width(), topLevelGeometry.height())
            - QPoint(scollbarThickness, scollbarThickness));

    QRect resizeCornerRect = QRect(resizeCornerTopLeft, QSize(scollbarThickness, scollbarThickness));
    return resizeCornerRect.intersected(pageClient->geometryRelativeToOwnerWidget());
#else
    return IntRect();
#endif
}
QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
                                       QString *initialDirectory,
                                       const QStringList &filterList,
                                       QString *selectedFilter,
                                       int selectedFilterIndex)
{
    QStringList result;
    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);
    // Multiple selection is allowed only in IFileOpenDialog.
    IFileOpenDialog *pfd = 0;
    HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog,
                                  NULL,
                                  CLSCTX_INPROC_SERVER,
                                  IID_PPV_ARGS(&pfd));

    if (SUCCEEDED(hr)) {
        qt_win_set_IFileDialogOptions(pfd, args.selection,
                                      args.directory, args.caption,
                                      filterList, QFileDialog::ExistingFiles,
                                      args.options);
        // Set the currently selected filter (one-based index).
        hr = pfd->SetFileTypeIndex(selectedFilterIndex+1);
        QWidget *parentWindow = args.parent;
        if (parentWindow)
            parentWindow = parentWindow->window();
        else
            parentWindow = QApplication::activeWindow();
        // Show the file dialog.
        hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
        if (SUCCEEDED(hr)) {
            // Retrieve the results.
            IShellItemArray *psiaResults;
            hr = pfd->GetResults(&psiaResults);
            if (SUCCEEDED(hr)) {
                DWORD numItems = 0;
                psiaResults->GetCount(&numItems);
                for (DWORD i = 0; i<numItems; i++) {
                    IShellItem *psi = 0;
                    hr = psiaResults->GetItemAt(i, &psi);
                    if (SUCCEEDED(hr)) {
                        // Retrieve the file name from shell item.
                        wchar_t *pszPath;
                        hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                        if (SUCCEEDED(hr)) {
                            QString fileName = QString::fromWCharArray(pszPath);
                            result.append(fileName);
                            CoTaskMemFree(pszPath);
                        }
                        psi->Release(); // Free the current item.
                    }
                }
                psiaResults->Release(); // Free the array of items.
            }
        }
    }
    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (!result.isEmpty()) {
        // Retrieve the current folder name.
        IShellItem *psi = 0;
        hr = pfd->GetFolder(&psi);
        if (SUCCEEDED(hr)) {
            wchar_t *pszPath;
            hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
            if (SUCCEEDED(hr)) {
                *initialDirectory = QString::fromWCharArray(pszPath);
                CoTaskMemFree(pszPath);
            }
            psi->Release();
        }
        // Retrieve the currently selected filter.
        if (selectedFilter) {
            quint32 filetype = 0;
            hr = pfd->GetFileTypeIndex(&filetype);
            if (SUCCEEDED(hr) && filetype && filetype <= (quint32)filterList.length()) {
                // This is a one-based index, not zero-based.
                *selectedFilter = filterList[filetype-1];
            }
        }
    }
    if (pfd)
        pfd->Release();
    return result;
}
int QPageSetupDialog::exec()
{
    Q_D(QPageSetupDialog);

    if (d->printer->outputFormat() != QPrinter::NativeFormat)
        return Rejected;

    QWin32PrintEngine *engine = static_cast<QWin32PrintEngine*>(d->printer->paintEngine());
    QWin32PrintEnginePrivate *ep = static_cast<QWin32PrintEnginePrivate *>(engine->d_ptr.data());

    PAGESETUPDLG psd;
    memset(&psd, 0, sizeof(PAGESETUPDLG));
    psd.lStructSize = sizeof(PAGESETUPDLG);

    // we need a temp DEVMODE struct if we don't have a global DEVMODE
    HGLOBAL hDevMode = 0;
    int devModeSize = 0;
    if (!ep->globalDevMode) {
        devModeSize = sizeof(DEVMODE) + ep->devMode->dmDriverExtra;
        hDevMode = GlobalAlloc(GHND, devModeSize);
        if (hDevMode) {
            void *dest = GlobalLock(hDevMode);
            memcpy(dest, ep->devMode, devModeSize);
            GlobalUnlock(hDevMode);
        }
        psd.hDevMode = hDevMode;
    } else {
        psd.hDevMode = ep->devMode;
    }

    HGLOBAL *tempDevNames = ep->createDevNames();
    psd.hDevNames = tempDevNames;

    QWidget *parent = parentWidget();
    parent = parent ? parent->window() : QApplication::activeWindow();
    Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
    psd.hwndOwner = parent ? parent->winId() : 0;

    QRect paperRect = d->printer->paperRect();
    QRect pageRect = d->printer->pageRect();

    psd.Flags = PSD_MARGINS;
    double multiplier = 1;
    switch (QLocale::system().measurementSystem()) {
    case QLocale::MetricSystem:
        psd.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS;
        multiplier = 1;
        break;
    case QLocale::ImperialSystem:
        psd.Flags |= PSD_INTHOUSANDTHSOFINCHES;
        multiplier = 25.4/10;
        break;
    }

    QRect marginRect = ep->getPageMargins();
    psd.rtMargin.left   = marginRect.left()   / multiplier;
    psd.rtMargin.top    = marginRect.top()    / multiplier;
    psd.rtMargin.right  = marginRect.width()  / multiplier;;
    psd.rtMargin.bottom = marginRect.height() / multiplier;;

    bool result = PageSetupDlg(&psd);
    if (result) {
        ep->readDevnames(psd.hDevNames);
        ep->readDevmode(psd.hDevMode);

        QRect theseMargins = QRect(psd.rtMargin.left   * multiplier,
                                   psd.rtMargin.top    * multiplier,
                                   psd.rtMargin.right  * multiplier,
                                   psd.rtMargin.bottom * multiplier);

        if (theseMargins != marginRect) {
            ep->setPageMargins(psd.rtMargin.left   * multiplier,
                               psd.rtMargin.top    * multiplier,
                               psd.rtMargin.right  * multiplier,
                               psd.rtMargin.bottom * multiplier);
        }

        ep->updateCustomPaperSize();

        // copy from our temp DEVMODE struct
        if (!ep->globalDevMode && hDevMode) {
            void *src = GlobalLock(hDevMode);
            memcpy(ep->devMode, src, devModeSize);
            GlobalUnlock(hDevMode);
        }
    }

    if (!ep->globalDevMode && hDevMode)
        GlobalFree(hDevMode);
    GlobalFree(tempDevNames);
    done(result);
    return result;
}
int QPrintDialogPrivate::openWindowsPrintDialogModally()
{
    Q_Q(QPrintDialog);
    QWidget *parent = q->parentWidget();
    if (parent)
        parent = parent->window();
    else
        parent = QApplication::activeWindow();

    // If there is no window, fall back to the print dialog itself
    if (parent == 0)
        parent = q;

    QWidget modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);

    HGLOBAL *tempDevNames = ep->createDevNames();

    bool done;
    bool result;
    bool doPrinting;

    PRINTPAGERANGE pageRange;
    PRINTDLGEX pd;
    memset(&pd, 0, sizeof(PRINTDLGEX));
    pd.lStructSize = sizeof(PRINTDLGEX);
    pd.lpPageRanges = &pageRange;
    qt_win_setup_PRINTDLGEX(&pd, parent, q, this, tempDevNames);

    do {
        done = true;
        doPrinting = false;
        result = (PrintDlgEx(&pd) == S_OK);
        if (result && (pd.dwResultAction == PD_RESULT_PRINT
                       || pd.dwResultAction == PD_RESULT_APPLY))
        {
            doPrinting = (pd.dwResultAction == PD_RESULT_PRINT);
            if ((pd.Flags & PD_PAGENUMS)
                && (pd.lpPageRanges[0].nFromPage > pd.lpPageRanges[0].nToPage))
            {
                pd.lpPageRanges[0].nFromPage = 1;
                pd.lpPageRanges[0].nToPage = 1;
                done = false;
            }
            if (pd.hDC == 0)
                result = false;
        }

        if (!done) {
            QMessageBox::warning(0, QPrintDialog::tr("Print"),
                                 QPrintDialog::tr("The 'From' value cannot be greater than the 'To' value."),
                                 QPrintDialog::tr("OK"));
        }
    } while (!done);

    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    // write values back...
    if (result && (pd.dwResultAction == PD_RESULT_PRINT
                   || pd.dwResultAction == PD_RESULT_APPLY))
    {
        qt_win_read_back_PRINTDLGEX(&pd, q, this);
        // update printer validity
        printer->d_func()->validPrinter = !ep->name.isEmpty();
    }

    // Cleanup...
    GlobalFree(tempDevNames);

    q->done(result && doPrinting);

    return result && doPrinting;
}
Example #26
0
QStringList qt_mac_get_open_file_names(const QFileDialogArgs &args, QString *pwd,
                                       QString *selectedFilter)
{
    QWidget *parent = args.parent;
    OSErr err;
    QStringList retstrl;

    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    options.modality = kWindowModalityAppModal;
    options.optionFlags |= kNavSupportPackages;
    if (args.options & QFileDialog::DontConfirmOverwrite)
        options.optionFlags |= kNavDontConfirmReplacement;
    if (args.mode != QFileDialog::ExistingFiles)
        options.optionFlags &= ~kNavAllowMultipleFiles;

    if (!args.caption.isEmpty())
        options.windowTitle = QCFString::toCFStringRef(args.caption);

    static const int w = 450, h = 350;
    options.location.h = options.location.v = -1;
    if (parent && parent->isVisible()) {
        WindowClass wclass;
        GetWindowClass(qt_mac_window_for(parent), &wclass);
        if (!(args.options & QFileDialog::DontUseSheet) && (wclass == kDocumentWindowClass ||
                                                            wclass == kFloatingWindowClass || wclass == kMovableModalWindowClass)) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = QCFString::toCFStringRef(s);
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            const int border = 10;
            if (options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + border;
            if (options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + border;
            if (options.location.h < r.left())
                options.location.h = r.left() + border;
            if (options.location.v < r.top())
                options.location.v = r.top() + border;
        }
#if 0
    } else if (QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if (last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
#endif
    }

    QList<qt_mac_filter_name*> filts = qt_mac_make_filters_list(args.filter);
    qt_mac_nav_filter_type t;
    t.saveDialog = false;
    t.index = 0;
    t.filts = &filts;
    if (filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef) * filts.count()));
        for (QList<qt_mac_filter_name*>::const_iterator it = filts.constBegin();
             it != filts.constEnd(); ++it)
            arr[i++] = QCFString::toCFStringRef((*it)->description);
        options.popupExtension = CFArrayCreate(0, reinterpret_cast<const void **>(arr), filts.count(), 0);
    }

    NavDialogRef dlg;
    if (args.mode == QFileDialog::DirectoryOnly ||
        args.mode == QFileDialog::Directory) {
        if (NavCreateChooseFolderDialog(&options, make_navProcUPP(), 0, 0, &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    } else {
        if (NavCreateGetFileDialog(&options, 0, make_navProcUPP(), 0,
                                  make_navFilterUPP(), (void *) (filts.isEmpty() ? 0 : &t),
                                  &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    }
    if (pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }

    NavDialogRun(dlg);

    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = qt_mac_make_filters_list(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }

    if (options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, Qt::Sheet);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while (g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if (!(NavDialogGetUserAction(dlg) &
          (kNavUserActionOpen | kNavUserActionChoose | kNavUserActionNewFolder))) {
        NavDialogDispose(dlg);
        return retstrl;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if (!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstrl;
    }

    for (long index = 1; index <= count; index++) {
        FSRef ref;
        err = AEGetNthPtr(&(ret.selection), index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
        if (err != noErr)
            break;

        if (!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstrl.append(QString::fromUtf8((const char *)str_buffer));
    }
    NavDisposeReply(&ret);
    if (selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstrl;
}
Example #27
0
KWebPage::KWebPage(QObject *parent, Integration flags)
         :QWebPage(parent), d(new KWebPagePrivate(this))
{ 
    // KDE KParts integration for <embed> tag...
    if (!flags || (flags & KPartsIntegration))
        setPluginFactory(new KWebPluginFactory(this));

    QWidget *parentWidget = qobject_cast<QWidget*>(parent);
    d->window = (parentWidget ? parentWidget->window() : 0);

    // KDE IO (KIO) integration...
    if (!flags || (flags & KIOIntegration)) {
        KIO::Integration::AccessManager *manager = new KIO::Integration::AccessManager(this);
        // Disable QtWebKit's internal cache to avoid duplication with the one in KIO...
        manager->setCache(0);
        manager->setWindow(d->window);
        manager->setEmitReadyReadOnMetaDataChange(true);
        setNetworkAccessManager(manager);
    }

    // KWallet integration...
    if (!flags || (flags & KWalletIntegration)) {
        setWallet(new KWebWallet(0, (d->window ? d->window->winId() : 0) ));
    }

    setActionIcon(action(Back), KIcon("go-previous"));
    setActionIcon(action(Forward), KIcon("go-next"));
    setActionIcon(action(Reload), KIcon("view-refresh"));
    setActionIcon(action(Stop), KIcon("process-stop"));
    setActionIcon(action(Cut), KIcon("edit-cut"));
    setActionIcon(action(Copy), KIcon("edit-copy"));
    setActionIcon(action(Paste), KIcon("edit-paste"));
    setActionIcon(action(Undo), KIcon("edit-undo"));
    setActionIcon(action(Redo), KIcon("edit-redo"));
    setActionIcon(action(InspectElement), KIcon("view-process-all"));
    setActionIcon(action(OpenLinkInNewWindow), KIcon("window-new"));
    setActionIcon(action(OpenFrameInNewWindow), KIcon("window-new"));
    setActionIcon(action(OpenImageInNewWindow), KIcon("window-new"));
    setActionIcon(action(CopyLinkToClipboard), KIcon("edit-copy"));
    setActionIcon(action(CopyImageToClipboard), KIcon("edit-copy"));
    setActionIcon(action(ToggleBold), KIcon("format-text-bold"));
    setActionIcon(action(ToggleItalic), KIcon("format-text-italic"));
    setActionIcon(action(ToggleUnderline), KIcon("format-text-underline"));
    setActionIcon(action(DownloadLinkToDisk), KIcon("document-save"));
    setActionIcon(action(DownloadImageToDisk), KIcon("document-save"));

    settings()->setWebGraphic(QWebSettings::MissingPluginGraphic, KIcon("preferences-plugin").pixmap(32, 32));
    settings()->setWebGraphic(QWebSettings::MissingImageGraphic, KIcon("image-missing").pixmap(32, 32));
    settings()->setWebGraphic(QWebSettings::DefaultFrameIconGraphic, KIcon("applications-internet").pixmap(32, 32));

    setActionShortcut(action(Back), KStandardShortcut::back());
    setActionShortcut(action(Forward), KStandardShortcut::forward());
    setActionShortcut(action(Reload), KStandardShortcut::reload());
    setActionShortcut(action(Stop), KShortcut(QKeySequence(Qt::Key_Escape)));
    setActionShortcut(action(Cut), KStandardShortcut::cut());
    setActionShortcut(action(Copy), KStandardShortcut::copy());
    setActionShortcut(action(Paste), KStandardShortcut::paste());
    setActionShortcut(action(Undo), KStandardShortcut::undo());
    setActionShortcut(action(Redo), KStandardShortcut::redo());
    setActionShortcut(action(SelectAll), KStandardShortcut::selectAll());
}
QString qt_win_get_existing_directory(const QFileDialogArgs &args)
{
    QString currentDir = QDir::currentPath();
    QString result;
    QWidget *parent = args.parent;
    if (parent)
        parent = parent->window();
    else
        parent = QApplication::activeWindow();
    if (parent)
        parent->createWinId();

    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);

    QString initDir = QDir::toNativeSeparators(args.directory);
    wchar_t path[MAX_PATH];
    wchar_t initPath[MAX_PATH];
    initPath[0] = 0;
    path[0] = 0;
    tTitle = args.caption;

#if !defined(Q_WS_WINCE)
    BROWSEINFO bi;
#else
    qt_BROWSEINFO bi;
#endif

    Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
    bi.hwndOwner = (parent ? parent->winId() : 0);
    bi.pidlRoot = NULL;
    //### This does not seem to be respected? - the dialog always displays "Browse for folder"
    bi.lpszTitle = (wchar_t*)tTitle.utf16();
    bi.pszDisplayName = initPath;
    bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
    bi.lpfn = winGetExistDirCallbackProc;
    bi.lParam = LPARAM(&initDir);

    qt_win_resolve_libs();
    if (ptrSHBrowseForFolder) {
        LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder((BROWSEINFO*)&bi);
        if (pItemIDList) {
            ptrSHGetPathFromIDList(pItemIDList, path);
            IMalloc *pMalloc;
            if (ptrSHGetMalloc(&pMalloc) == NOERROR) {
                pMalloc->Free(pItemIDList);
                pMalloc->Release();
                result = QString::fromWCharArray(path);
            }
        }
    }
    tTitle = QString();

    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (!result.isEmpty())
        result.replace(QLatin1Char('\\'), QLatin1Char('/'));
    return result;
}
Example #29
0
QString qt_mac_get_save_file_name(const QFileDialogArgs &args, QString *pwd,
                                  QString *selectedFilter)
{
    QWidget *parent = args.parent;
    OSErr err;
    QString retstr;
    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    static const int w = 450, h = 350;
    if (args.options & QFileDialog::DontConfirmOverwrite)
        options.optionFlags |= kNavDontConfirmReplacement;
    options.modality = kWindowModalityAppModal;
    options.location.h = options.location.v = -1;
    if (!args.directory.isEmpty())
        options.saveFileName = QCFString::toCFStringRef(args.selection);
    if (!args.caption.isEmpty())
        options.windowTitle = QCFString::toCFStringRef(args.caption);
    if (parent && parent->isVisible()) {
        WindowClass wclass;
        GetWindowClass(qt_mac_window_for(parent), &wclass);
        if (!(args.options & QFileDialog::DontUseSheet) && (wclass == kDocumentWindowClass ||
                                                            wclass == kFloatingWindowClass || wclass == kMovableModalWindowClass)) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);

            // The parent needs to be active for the sheet to get keyboard focus.
            if (!parent->isActiveWindow())
                parent->activateWindow();
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = CFStringCreateWithCharacters(0, (UniChar *)s.unicode(), s.length());
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            if (options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + 10;
            if (options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + 10;
        }
#if 0
    } else if (QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if (last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
#endif
    }

    QList<qt_mac_filter_name*> filts = qt_mac_make_filters_list(args.filter);
    qt_mac_nav_filter_type t;
    t.saveDialog = true;
    t.index = 0;
    t.filts = &filts;
    if (filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef) * filts.count()));
        for (QList<qt_mac_filter_name*>::const_iterator it = filts.constBegin();
             it != filts.constEnd(); ++it)
            arr[i++] = QCFString::toCFStringRef((*it)->description);
        options.popupExtension = CFArrayCreate(0, reinterpret_cast<const void **>(arr), filts.count(), 0);
    }

    NavDialogRef dlg;
    if (NavCreatePutFileDialog(&options, 'cute', kNavGenericSignature, make_navProcUPP(),
                               static_cast<void *>(filts.isEmpty() ? 0 : &t), &dlg)) {
        qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
        return retstr;
    }
    if (pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }
    NavDialogRun(dlg);
    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = qt_mac_make_filters_list(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }
    if (options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, Qt::Sheet);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while (g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if (NavDialogGetUserAction(dlg) != kNavUserActionSaveAs) {
        NavDialogDispose(dlg);
        return retstr;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if (!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstr;
    }

    AEKeyword        keyword;
    DescType    type;
    Size        size;
    FSRef ref;
    err = AEGetNthPtr(&(ret.selection), 1, typeFSRef, &keyword,
                      &type, &ref, sizeof(ref), &size);
    if (err == noErr) {
        if (!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstr = QString::fromUtf8((const char *)str_buffer);
        //now filename
        CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8);
        retstr += QLatin1String("/") + QString::fromUtf8((const char *)str_buffer);
    }
    NavDisposeReply(&ret);
    if (selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstr;
}
Example #30
0
void QAbstractButtonPrivate::moveFocus(int key)
{
    QList<QAbstractButton *> buttonList = queryButtonList();;
#ifndef QT_NO_BUTTONGROUP
    bool exclusive = group ? group->d_func()->exclusive : autoExclusive;
#else
    bool exclusive = autoExclusive;
#endif
    QWidget *f = QApplication::focusWidget();
    QAbstractButton *fb = qobject_cast<QAbstractButton *>(f);
    if (!fb || !buttonList.contains(fb))
        return;

    QAbstractButton *candidate = 0;
    int bestScore = -1;
    QRect target = f->rect().translated(f->mapToGlobal(QPoint(0,0)));
    QPoint goal = target.center();
    uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;

    for (int i = 0; i < buttonList.count(); ++i) {
        QAbstractButton *button = buttonList.at(i);
        if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() &&
                (autoExclusive || (button->focusPolicy() & focus_flag) == focus_flag)) {
            QRect buttonRect = button->rect().translated(button->mapToGlobal(QPoint(0,0)));
            QPoint p = buttonRect.center();

            //Priority to widgets that overlap on the same coordinate.
            //In that case, the distance in the direction will be used as significant score,
            //take also in account orthogonal distance in case two widget are in the same distance.
            int score;
            if ((buttonRect.x() < target.right() && target.x() < buttonRect.right())
                    && (key == Qt::Key_Up || key == Qt::Key_Down)) {
                //one item's is at the vertical of the other
                score = (qAbs(p.y() - goal.y()) << 16) + qAbs(p.x() - goal.x());
            } else if ((buttonRect.y() < target.bottom() && target.y() < buttonRect.bottom())
                       && (key == Qt::Key_Left || key == Qt::Key_Right) ) {
                //one item's is at the horizontal of the other
                score = (qAbs(p.x() - goal.x()) << 16) + qAbs(p.y() - goal.y());
            } else {
                score = (1 << 30) + (p.y() - goal.y()) * (p.y() - goal.y()) + (p.x() - goal.x()) * (p.x() - goal.x());
            }

            if (score > bestScore && candidate)
                continue;

            switch(key) {
            case Qt::Key_Up:
                if (p.y() < goal.y()) {
                    candidate = button;
                    bestScore = score;
                }
                break;
            case Qt::Key_Down:
                if (p.y() > goal.y()) {
                    candidate = button;
                    bestScore = score;
                }
                break;
            case Qt::Key_Left:
                if (p.x() < goal.x()) {
                    candidate = button;
                    bestScore = score;
                }
                break;
            case Qt::Key_Right:
                if (p.x() > goal.x()) {
                    candidate = button;
                    bestScore = score;
                }
                break;
            }
        }
    }

    if (exclusive
#ifdef QT_KEYPAD_NAVIGATION
            && !QApplication::keypadNavigationEnabled()
#endif
            && candidate
            && fb->d_func()->checked
            && candidate->d_func()->checkable)
        candidate->click();

    if (candidate) {
        if (key == Qt::Key_Up || key == Qt::Key_Left)
            candidate->setFocus(Qt::BacktabFocusReason);
        else
            candidate->setFocus(Qt::TabFocusReason);
    }
}