diff options
author | Thierry Bastian <thierry.bastian@nokia.com> | 2011-05-19 12:15:26 (GMT) |
---|---|---|
committer | Thierry Bastian <thierry.bastian@nokia.com> | 2011-05-19 12:15:26 (GMT) |
commit | 37c4cd4801106112b638ed9d2164b87bbc0a0d1e (patch) | |
tree | 3dcc9e1b9908328d1355f5746fd77de7030b547f /src/gui | |
parent | b6a6953d21a95c402e8a5010c1ea5131509eeea3 (diff) | |
parent | 35b5f15c3fe5c2f1f0d046d09b9d95dee3bb91b5 (diff) | |
download | Qt-37c4cd4801106112b638ed9d2164b87bbc0a0d1e.zip Qt-37c4cd4801106112b638ed9d2164b87bbc0a0d1e.tar.gz Qt-37c4cd4801106112b638ed9d2164b87bbc0a0d1e.tar.bz2 |
Merge branch '4.8-upstream'
Diffstat (limited to 'src/gui')
149 files changed, 2740 insertions, 5527 deletions
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp index 48cbec3..78918cc 100644 --- a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp +++ b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp @@ -451,8 +451,8 @@ static QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> getFactor(qreal valu static qreal interpolate(const QPair<QGraphicsAnchorLayoutPrivate::Interval, qreal> &factor, qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max) { - qreal lower; - qreal upper; + qreal lower = 0; + qreal upper = 0; switch (factor.first) { case QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred: diff --git a/src/gui/graphicsview/qgraphicslayout.cpp b/src/gui/graphicsview/qgraphicslayout.cpp index 904a3de..a67ae48 100644 --- a/src/gui/graphicsview/qgraphicslayout.cpp +++ b/src/gui/graphicsview/qgraphicslayout.cpp @@ -167,7 +167,7 @@ QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutItem *parent) " neither a QGraphicsWidget nor QGraphicsLayout"); } } - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, QSizePolicy::DefaultType); + d_func()->sizePolicy = QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, QSizePolicy::DefaultType); setOwnedByLayout(true); } @@ -188,7 +188,7 @@ QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutPrivate &dd, QGraphicsLayoutItem " neither a QGraphicsWidget nor QGraphicsLayout"); } } - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, QSizePolicy::DefaultType); + d_func()->sizePolicy = QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, QSizePolicy::DefaultType); setOwnedByLayout(true); } @@ -269,12 +269,20 @@ void QGraphicsLayout::activate() return; Q_ASSERT(!parentItem->isLayout()); - setGeometry(parentItem->contentsRect()); // relayout children + if (QGraphicsLayout::instantInvalidatePropagation()) { + QGraphicsWidget *parentWidget = static_cast<QGraphicsWidget*>(parentItem); + if (!parentWidget->parentLayoutItem()) { + // we've reached the topmost widget, resize it + bool wasResized = parentWidget->testAttribute(Qt::WA_Resized); + parentWidget->resize(parentWidget->size()); + parentWidget->setAttribute(Qt::WA_Resized, wasResized); + } - // ### bug, should be parentItem ? - parentLayoutItem()->updateGeometry(); // bubble up; will set activated to false - // ### too many resizes? maybe we should walk up the chain to the - // ### top-level layouted layoutItem and call activate there. + setGeometry(parentItem->contentsRect()); // relayout children + } else { + setGeometry(parentItem->contentsRect()); // relayout children + parentLayoutItem()->updateGeometry(); + } } /*! @@ -300,32 +308,36 @@ bool QGraphicsLayout::isActivated() const */ void QGraphicsLayout::invalidate() { - // only mark layouts as invalid (activated = false) if we can post a LayoutRequest event. - QGraphicsLayoutItem *layoutItem = this; - while (layoutItem && layoutItem->isLayout()) { - // we could call updateGeometry(), but what if that method - // does not call the base implementation? In addition, updateGeometry() - // does more than we need. - layoutItem->d_func()->sizeHintCacheDirty = true; - layoutItem->d_func()->sizeHintWithConstraintCacheDirty = true; - layoutItem = layoutItem->parentLayoutItem(); - } - if (layoutItem) { - layoutItem->d_func()->sizeHintCacheDirty = true; - layoutItem->d_func()->sizeHintWithConstraintCacheDirty = true; - } - - bool postIt = layoutItem ? !layoutItem->isLayout() : false; - if (postIt) { - layoutItem = this; - while (layoutItem && layoutItem->isLayout() - && static_cast<QGraphicsLayout*>(layoutItem)->d_func()->activated) { - static_cast<QGraphicsLayout*>(layoutItem)->d_func()->activated = false; + if (QGraphicsLayout::instantInvalidatePropagation()) { + updateGeometry(); + } else { + // only mark layouts as invalid (activated = false) if we can post a LayoutRequest event. + QGraphicsLayoutItem *layoutItem = this; + while (layoutItem && layoutItem->isLayout()) { + // we could call updateGeometry(), but what if that method + // does not call the base implementation? In addition, updateGeometry() + // does more than we need. + layoutItem->d_func()->sizeHintCacheDirty = true; + layoutItem->d_func()->sizeHintWithConstraintCacheDirty = true; layoutItem = layoutItem->parentLayoutItem(); } - if (layoutItem && !layoutItem->isLayout()) { - // If a layout has a parent that is not a layout it must be a QGraphicsWidget. - QApplication::postEvent(static_cast<QGraphicsWidget *>(layoutItem), new QEvent(QEvent::LayoutRequest)); + if (layoutItem) { + layoutItem->d_func()->sizeHintCacheDirty = true; + layoutItem->d_func()->sizeHintWithConstraintCacheDirty = true; + } + + bool postIt = layoutItem ? !layoutItem->isLayout() : false; + if (postIt) { + layoutItem = this; + while (layoutItem && layoutItem->isLayout() + && static_cast<QGraphicsLayout*>(layoutItem)->d_func()->activated) { + static_cast<QGraphicsLayout*>(layoutItem)->d_func()->activated = false; + layoutItem = layoutItem->parentLayoutItem(); + } + if (layoutItem && !layoutItem->isLayout()) { + // If a layout has a parent that is not a layout it must be a QGraphicsWidget. + QApplication::postEvent(static_cast<QGraphicsWidget *>(layoutItem), new QEvent(QEvent::LayoutRequest)); + } } } } @@ -335,12 +347,27 @@ void QGraphicsLayout::invalidate() */ void QGraphicsLayout::updateGeometry() { - QGraphicsLayoutItem::updateGeometry(); - if (QGraphicsLayoutItem *parentItem = parentLayoutItem()) { - if (parentItem->isLayout()) { + Q_D(QGraphicsLayout); + if (QGraphicsLayout::instantInvalidatePropagation()) { + d->activated = false; + QGraphicsLayoutItem::updateGeometry(); + + QGraphicsLayoutItem *parentItem = parentLayoutItem(); + if (!parentItem) + return; + + if (parentItem->isLayout()) + static_cast<QGraphicsLayout *>(parentItem)->invalidate(); + else parentItem->updateGeometry(); - } else { - invalidate(); + } else { + QGraphicsLayoutItem::updateGeometry(); + if (QGraphicsLayoutItem *parentItem = parentLayoutItem()) { + if (parentItem->isLayout()) { + parentItem->updateGeometry(); + } else { + invalidate(); + } } } } @@ -446,6 +473,50 @@ void QGraphicsLayout::addChildLayoutItem(QGraphicsLayoutItem *layoutItem) d->addChildLayoutItem(layoutItem); } +static bool g_instantInvalidatePropagation = false; + +/*! + \internal + \since 4.8 + \see instantInvalidatePropagation + + Calling this function with \a enable set to true will enable a feature that + makes propagation of invalidation up to ancestor layout items to be done in + one go. It will propagate up the parentLayoutItem() hierarchy until it has + reached the root. If the root item is a QGraphicsWidget, it will *post* a + layout request to it. When the layout request is consumed it will traverse + down the hierarchy of layouts and widgets and activate all layouts that is + invalid (not activated). This is the recommended behaviour. + + If not set it will also propagate up the parentLayoutItem() hierarchy, but + it will stop at the \i first \i widget it encounters, and post a layout + request to the widget. When the layout request is consumed, this might + cause it to continue propagation up to the parentLayoutItem() of the + widget. It will continue in this fashion until it has reached a widget with + no parentLayoutItem(). This strategy might cause drawing artifacts, since + it is not done in one go, and the consumption of layout requests might be + interleaved by consumption of paint events, which might cause significant + flicker. + Note, this is not the recommended behavior, but for compatibility reasons + this is the default behaviour. +*/ +void QGraphicsLayout::setInstantInvalidatePropagation(bool enable) +{ + g_instantInvalidatePropagation = enable; +} + +/*! + \internal + \since 4.8 + \see setInstantInvalidatePropagation + + returns true if the complete widget/layout hierarchy is rearranged in one go. +*/ +bool QGraphicsLayout::instantInvalidatePropagation() +{ + return g_instantInvalidatePropagation; +} + QT_END_NAMESPACE #endif //QT_NO_GRAPHICSVIEW diff --git a/src/gui/graphicsview/qgraphicslayout.h b/src/gui/graphicsview/qgraphicslayout.h index c622fb8..6031174 100644 --- a/src/gui/graphicsview/qgraphicslayout.h +++ b/src/gui/graphicsview/qgraphicslayout.h @@ -76,6 +76,8 @@ public: virtual QGraphicsLayoutItem *itemAt(int i) const = 0; virtual void removeAt(int index) = 0; + static void setInstantInvalidatePropagation(bool enable); + static bool instantInvalidatePropagation(); protected: QGraphicsLayout(QGraphicsLayoutPrivate &, QGraphicsLayoutItem *); void addChildLayoutItem(QGraphicsLayoutItem *layoutItem); diff --git a/src/gui/graphicsview/qgraphicslayout_p.cpp b/src/gui/graphicsview/qgraphicslayout_p.cpp index c325602..f73fb6a 100644 --- a/src/gui/graphicsview/qgraphicslayout_p.cpp +++ b/src/gui/graphicsview/qgraphicslayout_p.cpp @@ -180,8 +180,13 @@ void QGraphicsLayoutPrivate::activateRecursive(QGraphicsLayoutItem *item) { if (item->isLayout()) { QGraphicsLayout *layout = static_cast<QGraphicsLayout *>(item); - if (layout->d_func()->activated) - layout->invalidate(); + if (layout->d_func()->activated) { + if (QGraphicsLayout::instantInvalidatePropagation()) { + return; + } else { + layout->invalidate(); // ### LOOKS SUSPICIOUSLY WRONG!!??? + } + } for (int i = layout->count() - 1; i >= 0; --i) { QGraphicsLayoutItem *childItem = layout->itemAt(i); diff --git a/src/gui/graphicsview/qgraphicslinearlayout.cpp b/src/gui/graphicsview/qgraphicslinearlayout.cpp index 5591638..40f9b1d 100644 --- a/src/gui/graphicsview/qgraphicslinearlayout.cpp +++ b/src/gui/graphicsview/qgraphicslinearlayout.cpp @@ -275,17 +275,13 @@ void QGraphicsLinearLayout::insertItem(int index, QGraphicsLayoutItem *item) qWarning("QGraphicsLinearLayout::insertItem: cannot insert itself"); return; } - Q_ASSERT(item); - - //the order of the following instructions is very important because - //invalidating the layout before adding the child item will make the layout happen - //before we try to paint the item - invalidate(); d->addChildLayoutItem(item); + Q_ASSERT(item); d->fixIndex(&index); d->engine.insertRow(index, d->orientation); new QGridLayoutItem(&d->engine, item, d->gridRow(index), d->gridColumn(index), 1, 1, 0, index); + invalidate(); } /*! diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 675a5c5..141e305 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -354,8 +354,10 @@ void QGraphicsWidget::setGeometry(const QRectF &rect) newGeom = rect; newGeom.setSize(rect.size().expandedTo(effectiveSizeHint(Qt::MinimumSize)) .boundedTo(effectiveSizeHint(Qt::MaximumSize))); - if (newGeom == d->geom) - return; + + if (newGeom == d->geom) { + goto relayoutChildrenAndReturn; + } // setPos triggers ItemPositionChange, which can adjust position wd->inSetGeometry = 1; @@ -363,8 +365,9 @@ void QGraphicsWidget::setGeometry(const QRectF &rect) wd->inSetGeometry = 0; newGeom.moveTopLeft(pos()); - if (newGeom == d->geom) - return; + if (newGeom == d->geom) { + goto relayoutChildrenAndReturn; + } // Update and prepare to change the geometry (remove from index) if the size has changed. if (wd->scene) { @@ -375,35 +378,54 @@ void QGraphicsWidget::setGeometry(const QRectF &rect) } // Update the layout item geometry - bool moved = oldPos != pos(); - if (moved) { - // Send move event. - QGraphicsSceneMoveEvent event; - event.setOldPos(oldPos); - event.setNewPos(pos()); - QApplication::sendEvent(this, &event); - if (wd->inSetPos) { - //set the new pos - d->geom.moveTopLeft(pos()); - emit geometryChanged(); - return; + { + bool moved = oldPos != pos(); + if (moved) { + // Send move event. + QGraphicsSceneMoveEvent event; + event.setOldPos(oldPos); + event.setNewPos(pos()); + QApplication::sendEvent(this, &event); + if (wd->inSetPos) { + //set the new pos + d->geom.moveTopLeft(pos()); + emit geometryChanged(); + goto relayoutChildrenAndReturn; + } + } + QSizeF oldSize = size(); + QGraphicsLayoutItem::setGeometry(newGeom); + // Send resize event + bool resized = newGeom.size() != oldSize; + if (resized) { + QGraphicsSceneResizeEvent re; + re.setOldSize(oldSize); + re.setNewSize(newGeom.size()); + if (oldSize.width() != newGeom.size().width()) + emit widthChanged(); + if (oldSize.height() != newGeom.size().height()) + emit heightChanged(); + QGraphicsLayout *lay = wd->layout; + if (QGraphicsLayout::instantInvalidatePropagation()) { + if (!lay || lay->isActivated()) { + QApplication::sendEvent(this, &re); + } + } else { + QApplication::sendEvent(this, &re); + } } } - QSizeF oldSize = size(); - QGraphicsLayoutItem::setGeometry(newGeom); - // Send resize event - bool resized = newGeom.size() != oldSize; - if (resized) { - QGraphicsSceneResizeEvent re; - re.setOldSize(oldSize); - re.setNewSize(newGeom.size()); - if (oldSize.width() != newGeom.size().width()) - emit widthChanged(); - if (oldSize.height() != newGeom.size().height()) - emit heightChanged(); - QApplication::sendEvent(this, &re); - } + emit geometryChanged(); +relayoutChildrenAndReturn: + if (QGraphicsLayout::instantInvalidatePropagation()) { + if (QGraphicsLayout *lay = wd->layout) { + if (!lay->isActivated()) { + QEvent layoutRequest(QEvent::LayoutRequest); + QApplication::sendEvent(this, &layoutRequest); + } + } + } } /*! @@ -1052,16 +1074,31 @@ void QGraphicsWidget::updateGeometry() QGraphicsLayoutItem *parentItem = parentLayoutItem(); if (parentItem && parentItem->isLayout()) { - parentItem->updateGeometry(); + if (QGraphicsLayout::instantInvalidatePropagation()) { + static_cast<QGraphicsLayout *>(parentItem)->invalidate(); + } else { + parentItem->updateGeometry(); + } } else { if (parentItem) { + // This is for custom layouting QGraphicsWidget *parentWid = parentWidget(); //### if (parentWid->isVisible()) QApplication::postEvent(parentWid, new QEvent(QEvent::LayoutRequest)); + } else { + /** + * If this is the topmost widget, post a LayoutRequest event to the widget. + * When the event is received, it will start flowing all the way down to the leaf + * widgets in one go. This will make a relayout flicker-free. + */ + if (QGraphicsLayout::instantInvalidatePropagation()) + QApplication::postEvent(static_cast<QGraphicsWidget *>(this), new QEvent(QEvent::LayoutRequest)); + } + if (!QGraphicsLayout::instantInvalidatePropagation()) { + bool wasResized = testAttribute(Qt::WA_Resized); + resize(size()); // this will restrict the size + setAttribute(Qt::WA_Resized, wasResized); } - bool wasResized = testAttribute(Qt::WA_Resized); - resize(size()); // this will restrict the size - setAttribute(Qt::WA_Resized, wasResized); } } diff --git a/src/gui/graphicsview/qgraphicswidget_p.cpp b/src/gui/graphicsview/qgraphicswidget_p.cpp index 4580055..63d7298 100644 --- a/src/gui/graphicsview/qgraphicswidget_p.cpp +++ b/src/gui/graphicsview/qgraphicswidget_p.cpp @@ -857,8 +857,6 @@ void QGraphicsWidgetPrivate::setWidth(qreal w) if (q->geometry().width() == w) return; - QRectF oldGeom = q->geometry(); - q->setGeometry(QRectF(q->x(), q->y(), w, height())); } @@ -882,8 +880,6 @@ void QGraphicsWidgetPrivate::setHeight(qreal h) if (q->geometry().height() == h) return; - QRectF oldGeom = q->geometry(); - q->setGeometry(QRectF(q->x(), q->y(), width(), h)); } diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp index 50b372e..25f6295 100644 --- a/src/gui/image/qimage.cpp +++ b/src/gui/image/qimage.cpp @@ -4449,6 +4449,8 @@ QImage QImage::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::Transf QSize newSize = size(); newSize.scale(s, aspectMode); + newSize.rwidth() = qMax(newSize.width(), 1); + newSize.rheight() = qMax(newSize.height(), 1); if (newSize == size()) return *this; diff --git a/src/gui/image/qpixmap.cpp b/src/gui/image/qpixmap.cpp index 34804e5..640864d 100644 --- a/src/gui/image/qpixmap.cpp +++ b/src/gui/image/qpixmap.cpp @@ -1224,12 +1224,8 @@ Qt::HANDLE QPixmap::handle() const { #if defined(Q_WS_X11) const QPixmapData *pd = pixmapData(); - if (pd) { - if (pd->classId() == QPixmapData::X11Class) - return static_cast<const QX11PixmapData*>(pd)->handle(); - else - qWarning("QPixmap::handle(): Pixmap is not an X11 class pixmap"); - } + if (pd && pd->classId() == QPixmapData::X11Class) + return static_cast<const QX11PixmapData*>(pd)->handle(); #endif return 0; } @@ -1518,6 +1514,8 @@ QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::Tran QSize newSize = size(); newSize.scale(s, aspectMode); + newSize.rwidth() = qMax(newSize.width(), 1); + newSize.rheight() = qMax(newSize.height(), 1); if (newSize == size()) return *this; diff --git a/src/gui/image/qpixmap_mac.cpp b/src/gui/image/qpixmap_mac.cpp index 72e2aa6..e107d88 100644 --- a/src/gui/image/qpixmap_mac.cpp +++ b/src/gui/image/qpixmap_mac.cpp @@ -54,6 +54,7 @@ #include <private/qpaintengine_mac_p.h> #include <private/qt_mac_p.h> #include <private/qt_cocoa_helpers_mac_p.h> +#include <private/qapplication_p.h> #include <limits.h> #include <string.h> @@ -73,12 +74,18 @@ static int qt_pixmap_serial = 0; Q_GUI_EXPORT quint32 *qt_mac_pixmap_get_base(const QPixmap *pix) { - return static_cast<QMacPixmapData*>(pix->data.data())->pixels; + if (QApplicationPrivate::graphics_system_name == QLatin1String("raster")) + return reinterpret_cast<quint32 *>(static_cast<QRasterPixmapData*>(pix->data.data())->buffer()->bits()); + else + return static_cast<QMacPixmapData*>(pix->data.data())->pixels; } Q_GUI_EXPORT int qt_mac_pixmap_get_bytes_per_line(const QPixmap *pix) { - return static_cast<QMacPixmapData*>(pix->data.data())->bytesPerRow; + if (QApplicationPrivate::graphics_system_name == QLatin1String("raster")) + return static_cast<QRasterPixmapData*>(pix->data.data())->buffer()->bytesPerLine(); + else + return static_cast<QMacPixmapData*>(pix->data.data())->bytesPerRow; } void qt_mac_cgimage_data_free(void *info, const void *memoryToFree, size_t) diff --git a/src/gui/image/qvolatileimage.cpp b/src/gui/image/qvolatileimage.cpp index 098e9a1..f5076e1 100644 --- a/src/gui/image/qvolatileimage.cpp +++ b/src/gui/image/qvolatileimage.cpp @@ -103,6 +103,11 @@ QVolatileImage &QVolatileImage::operator=(const QVolatileImage &rhs) return *this; } +bool QVolatileImage::paintingActive() const +{ + return d->pengine && d->pengine->isActive(); +} + bool QVolatileImage::isNull() const { return d->image.isNull(); diff --git a/src/gui/image/qvolatileimage_p.h b/src/gui/image/qvolatileimage_p.h index fc5d6b1..d835f45 100644 --- a/src/gui/image/qvolatileimage_p.h +++ b/src/gui/image/qvolatileimage_p.h @@ -71,6 +71,7 @@ public: ~QVolatileImage(); QVolatileImage &operator=(const QVolatileImage &rhs); + bool paintingActive() const; bool isNull() const; QImage::Format format() const; int width() const; diff --git a/src/gui/inputmethod/qcoefepinputcontext_p.h b/src/gui/inputmethod/qcoefepinputcontext_p.h index de3577f..57c1e45 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_p.h +++ b/src/gui/inputmethod/qcoefepinputcontext_p.h @@ -168,6 +168,7 @@ private: }; Q_GUI_EXPORT void qt_s60_setPartialScreenInputMode(bool enable); +Q_GUI_EXPORT void qt_s60_setPartialScreenAutomaticTranslation(bool enable); QT_END_NAMESPACE diff --git a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp index 06dc25c..23109e1 100644 --- a/src/gui/inputmethod/qcoefepinputcontext_s60.cpp +++ b/src/gui/inputmethod/qcoefepinputcontext_s60.cpp @@ -88,6 +88,11 @@ Q_GUI_EXPORT void qt_s60_setPartialScreenInputMode(bool enable) ic->update(); } +Q_GUI_EXPORT void qt_s60_setPartialScreenAutomaticTranslation(bool enable) +{ + S60->partial_keyboardAutoTranslation = enable; +} + QCoeFepInputContext::QCoeFepInputContext(QObject *parent) : QInputContext(parent), m_fepState(q_check_ptr(new CAknEdwinState)), // CBase derived object needs check on new @@ -235,21 +240,6 @@ bool QCoeFepInputContext::filterEvent(const QEvent *event) return false; switch (event->type()) { - case QEvent::MouseButtonPress: - // Alphanumeric keypad doesn't like it when we click and text is still getting displayed - // It ignores the mouse event, so we need to commit and send a selection event (which will get triggered - // after the commit) - if (!m_preeditString.isEmpty()) { - commitCurrentString(true); - - int pos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt(); - - QList<QInputMethodEvent::Attribute> selectAttributes; - selectAttributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, pos, 0, QVariant()); - QInputMethodEvent selectEvent(QLatin1String(""), selectAttributes); - sendEvent(selectEvent); - } - break; case QEvent::KeyPress: commitTemporaryPreeditString(); // fall through intended @@ -328,7 +318,10 @@ bool QCoeFepInputContext::filterEvent(const QEvent *event) if (sControl) { sControl->setIgnoreFocusChanged(false); } - return true; + //If m_pointerHandler has already been set, it means that fep inline editing is in progress. + //When this is happening, do not filter out pointer events. + if (!m_pointerHandler) + return true; } return false; @@ -380,18 +373,31 @@ void QCoeFepInputContext::commitTemporaryPreeditString() commitCurrentString(false); } -void QCoeFepInputContext::mouseHandler( int x, QMouseEvent *event) +void QCoeFepInputContext::mouseHandler(int x, QMouseEvent *event) { Q_ASSERT(focusWidget()); if (event->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton) { - commitCurrentString(true); - int pos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt(); + QWidget *proxy = focusWidget()->focusProxy(); + Qt::InputMethodHints currentHints = proxy ? proxy->inputMethodHints() : focusWidget()->inputMethodHints(); + + //If splitview is open and T9 word is tapped, pass the pointer event to pointer handler. + //This will open the "suggested words" list. Pass pointer position always as zero, to make + //full word replacement in case user makes a selection. + if (S60->partial_keyboard && S60->partialKeyboardOpen + && m_pointerHandler + && !(currentHints & Qt::ImhNoPredictiveText) + && (x > 0 && x < m_preeditString.length())) { + m_pointerHandler->HandlePointerEventInInlineTextL(TPointerEvent::EButton1Up, 0, 0); + } else { + commitCurrentString(true); + int pos = focusWidget()->inputMethodQuery(Qt::ImCursorPosition).toInt(); - QList<QInputMethodEvent::Attribute> attributes; - attributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, pos + x, 0, QVariant()); - QInputMethodEvent event(QLatin1String(""), attributes); - sendEvent(event); + QList<QInputMethodEvent::Attribute> attributes; + attributes << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, pos + x, 0, QVariant()); + QInputMethodEvent event(QLatin1String(""), attributes); + sendEvent(event); + } } } @@ -559,12 +565,13 @@ void QCoeFepInputContext::ensureFocusWidgetVisible(QWidget *widget) widget->resize(widget->width(), splitViewRect.height() - windowTop); } - if (gv->scene()) { + if (gv->scene() && S60->partial_keyboardAutoTranslation) { const QRectF microFocusRect = gv->scene()->inputMethodQuery(Qt::ImMicroFocus).toRectF(); gv->ensureVisible(microFocusRect); } } else { - translateInputWidget(); + if (S60->partial_keyboardAutoTranslation) + translateInputWidget(); } if (alwaysResize) diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp index d671496..0bf85c6 100644 --- a/src/gui/itemviews/qabstractitemview.cpp +++ b/src/gui/itemviews/qabstractitemview.cpp @@ -62,9 +62,6 @@ #include <qaccessible.h> #endif #include <private/qsoftkeymanager_p.h> -#ifndef QT_NO_GESTURE -# include <qscroller.h> -#endif QT_BEGIN_NAMESPACE @@ -194,40 +191,6 @@ void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index } } -#ifndef QT_NO_GESTURES - -// stores and restores the selection and current item when flicking -void QAbstractItemViewPrivate::_q_scrollerStateChanged() -{ - Q_Q(QAbstractItemView); - - if (QScroller *scroller = QScroller::scroller(viewport)) { - switch (scroller->state()) { - case QScroller::Pressed: - // store the current selection in case we start scrolling - if (q->selectionModel()) { - oldSelection = q->selectionModel()->selection(); - oldCurrent = q->selectionModel()->currentIndex(); - } - break; - - case QScroller::Dragging: - // restore the old selection if we really start scrolling - if (q->selectionModel()) { - q->selectionModel()->select(oldSelection, QItemSelectionModel::ClearAndSelect); - q->selectionModel()->setCurrentIndex(oldCurrent, QItemSelectionModel::NoUpdate); - } - // fall through - - default: - oldSelection = QItemSelection(); - oldCurrent = QModelIndex(); - break; - } - } -} - -#endif // QT_NO_GESTURES /*! \class QAbstractItemView @@ -1662,13 +1625,6 @@ bool QAbstractItemView::viewportEvent(QEvent *event) case QEvent::WindowDeactivate: d->viewport->update(); break; - case QEvent::ScrollPrepare: - executeDelayedItemsLayout(); -#ifndef QT_NO_GESTURES - connect(QScroller::scroller(d->viewport), SIGNAL(stateChanged(QScroller::State)), this, SLOT(_q_scrollerStateChanged()), Qt::UniqueConnection); -#endif - break; - default: break; } diff --git a/src/gui/itemviews/qabstractitemview.h b/src/gui/itemviews/qabstractitemview.h index f11f209..7043a5f 100644 --- a/src/gui/itemviews/qabstractitemview.h +++ b/src/gui/itemviews/qabstractitemview.h @@ -359,9 +359,6 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_modelDestroyed()) Q_PRIVATE_SLOT(d_func(), void _q_layoutChanged()) Q_PRIVATE_SLOT(d_func(), void _q_headerDataChanged()) -#ifndef QT_NO_GESTURES - Q_PRIVATE_SLOT(d_func(), void _q_scrollerStateChanged()) -#endif friend class QTreeViewPrivate; // needed to compile with MSVC friend class QAccessibleItemRow; diff --git a/src/gui/itemviews/qabstractitemview_p.h b/src/gui/itemviews/qabstractitemview_p.h index 6041e5e..d5a0d37 100644 --- a/src/gui/itemviews/qabstractitemview_p.h +++ b/src/gui/itemviews/qabstractitemview_p.h @@ -114,7 +114,6 @@ public: virtual void _q_modelDestroyed(); virtual void _q_layoutChanged(); void _q_headerDataChanged() { doDelayedItemsLayout(); } - void _q_scrollerStateChanged(); void fetchMore(); @@ -415,12 +414,6 @@ public: QAbstractItemView::ScrollMode verticalScrollMode; QAbstractItemView::ScrollMode horizontalScrollMode; -#ifndef QT_NO_GESTURES - // the selection before the last mouse down. In case we have to restore it for scrolling - QItemSelection oldSelection; - QModelIndex oldCurrent; -#endif - bool currentIndexSet; bool wrapItemText; diff --git a/src/gui/itemviews/qdatawidgetmapper.cpp b/src/gui/itemviews/qdatawidgetmapper.cpp index 745ef5a..dac4613 100644 --- a/src/gui/itemviews/qdatawidgetmapper.cpp +++ b/src/gui/itemviews/qdatawidgetmapper.cpp @@ -291,7 +291,7 @@ void QDataWidgetMapperPrivate::_q_modelDestroyed() \snippet doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp 0 After the call to toFirst(), \c mySpinBox displays the value \c{1}, \c myLineEdit - displays \c {Nokia Corporation and/or its subsidiary(-ies)} and \c myCountryChooser displays \c{Oslo}. The + displays \c{Qt Norway} and \c myCountryChooser displays \c{Oslo}. The navigational functions toFirst(), toNext(), toPrevious(), toLast() and setCurrentIndex() can be used to navigate in the model and update the widgets with contents from the model. diff --git a/src/gui/itemviews/qtableview.cpp b/src/gui/itemviews/qtableview.cpp index 59a3d15..e70f356 100644 --- a/src/gui/itemviews/qtableview.cpp +++ b/src/gui/itemviews/qtableview.cpp @@ -1300,7 +1300,6 @@ void QTableView::paintEvent(QPaintEvent *event) const QPen gridPen = QPen(gridColor, 0, d->gridStyle); const QHeaderView *verticalHeader = d->verticalHeader; const QHeaderView *horizontalHeader = d->horizontalHeader; - const QStyle::State state = option.state; const bool alternate = d->alternatingColors; const bool rightToLeft = isRightToLeft(); diff --git a/src/gui/kernel/qapplication_s60.cpp b/src/gui/kernel/qapplication_s60.cpp index 408c3b5..815d221 100644 --- a/src/gui/kernel/qapplication_s60.cpp +++ b/src/gui/kernel/qapplication_s60.cpp @@ -1360,6 +1360,23 @@ void QSymbianControl::PositionChanged() } } +// Search recursively if there is a child widget that is both visible and focused. +bool QSymbianControl::hasFocusedAndVisibleChild(QWidget *parentWidget) +{ + for (int i = 0; i < parentWidget->children().size(); ++i) { + QObject *object = parentWidget->children().at(i); + if (object && object->isWidgetType()) { + QWidget *w = static_cast<QWidget *>(object); + WId winId = w->internalWinId(); + if (winId && winId->IsFocused() && winId->IsVisible()) + return true; + if (hasFocusedAndVisibleChild(w)) + return true; + } + } + return false; +} + void QSymbianControl::FocusChanged(TDrawNow /* aDrawNow */) { if (m_ignoreFocusChanged || (qwidget->windowType() & Qt::WindowType_Mask) == Qt::Desktop) @@ -1392,17 +1409,9 @@ void QSymbianControl::FocusChanged(TDrawNow /* aDrawNow */) if (qwidget->isWindow()) S60->setRecursiveDecorationsVisibility(qwidget, qwidget->windowState()); #endif - } else if (QApplication::activeWindow() == qwidget->window()) { - bool focusedControlFound = false; - WId winId = 0; - for (QWidget *w = qwidget->parentWidget(); w && (winId = w->internalWinId()); w = w->parentWidget()) { - if (winId->IsFocused() && winId->IsVisible()) { - focusedControlFound = true; - break; - } else if (w->isWindow()) - break; - } - if (!focusedControlFound) { + } else { + QWidget *parentWindow = qwidget->window(); + if (QApplication::activeWindow() == parentWindow && !hasFocusedAndVisibleChild(parentWindow)) { if (CCoeEnv::Static()->AppUi()->IsDisplayingMenuOrDialog() || S60->menuBeingConstructed) { QWidget *fw = QApplication::focusWidget(); if (fw) { @@ -1481,8 +1490,10 @@ void QSymbianControl::HandleResourceChange(int resourceType) } if (ic && isSplitViewWidget(widget)) { if (resourceType == KSplitViewCloseEvent) { + S60->partialKeyboardOpen = false; ic->resetSplitViewWidget(); } else { + S60->partialKeyboardOpen = true; ic->ensureFocusWidgetVisible(widget); } } @@ -1509,6 +1520,10 @@ void QSymbianControl::HandleResourceChange(int resourceType) #ifdef Q_WS_S60 case KEikDynamicLayoutVariantSwitch: { +#ifdef QT_SOFTKEYS_ENABLED + // Update needed just in case softkeys contain icons + QSoftKeyManager::updateSoftKeys(); +#endif handleClientAreaChange(); // Send resize event to trigger desktopwidget workAreaResized signal if (qt_desktopWidget) { @@ -2703,6 +2718,9 @@ QS60ThreadLocalData::QS60ThreadLocalData() QS60ThreadLocalData::~QS60ThreadLocalData() { + for (int i = 0; i < releaseFuncs.count(); ++i) + releaseFuncs[i](); + releaseFuncs.clear(); if (!usingCONEinstances) { delete screenDevice; wsSession.Close(); diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 6658300..63e2319 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -237,6 +237,7 @@ static void resolveAygLibs() # define FE_FONTSMOOTHINGCLEARTYPE 0x0002 #endif +Q_GUI_EXPORT qreal qt_fontsmoothing_gamma; Q_GUI_EXPORT bool qt_cleartype_enabled; Q_GUI_EXPORT bool qt_win_owndc_required; // CS_OWNDC is required if we use the GL graphicssystem as default @@ -653,8 +654,18 @@ static void qt_win_read_cleartype_settings() if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0)) qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE); #endif -} + int winSmooth; + if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0)) { + qt_fontsmoothing_gamma = winSmooth / qreal(1000.0); + } else { + qt_fontsmoothing_gamma = 1.0; + } + + // Safeguard ourselves against corrupt registry values... + if (qt_fontsmoothing_gamma > 5 || qt_fontsmoothing_gamma < 1) + qt_fontsmoothing_gamma = qreal(1.4); +} static void qt_set_windows_resources() { diff --git a/src/gui/kernel/qapplication_x11.cpp b/src/gui/kernel/qapplication_x11.cpp index 20542ea..577d93b 100644 --- a/src/gui/kernel/qapplication_x11.cpp +++ b/src/gui/kernel/qapplication_x11.cpp @@ -2018,15 +2018,12 @@ void qt_init(QApplicationPrivate *priv, int, (PtrXRRRootToScreen) xrandrLib.resolve("XRRRootToScreen"); X11->ptrXRRQueryExtension = (PtrXRRQueryExtension) xrandrLib.resolve("XRRQueryExtension"); - X11->ptrXRRSizes = - (PtrXRRSizes) xrandrLib.resolve("XRRSizes"); } # else X11->ptrXRRSelectInput = XRRSelectInput; X11->ptrXRRUpdateConfiguration = XRRUpdateConfiguration; X11->ptrXRRRootToScreen = XRRRootToScreen; X11->ptrXRRQueryExtension = XRRQueryExtension; - X11->ptrXRRSizes = XRRSizes; # endif if (X11->ptrXRRQueryExtension diff --git a/src/gui/kernel/qclipboard.h b/src/gui/kernel/qclipboard.h index b55bdc6..019917e 100644 --- a/src/gui/kernel/qclipboard.h +++ b/src/gui/kernel/qclipboard.h @@ -112,6 +112,7 @@ protected: friend class QBaseApplication; friend class QDragManager; friend class QMimeSource; + friend class QPlatformClipboard; private: Q_DISABLE_COPY(QClipboard) diff --git a/src/gui/kernel/qcursor_x11.cpp b/src/gui/kernel/qcursor_x11.cpp index d0ed98e..0bc7250 100644 --- a/src/gui/kernel/qcursor_x11.cpp +++ b/src/gui/kernel/qcursor_x11.cpp @@ -55,6 +55,9 @@ #endif // QT_NO_XCURSOR #ifndef QT_NO_XFIXES +#ifndef Status +#define Status int +#endif # include <X11/extensions/Xfixes.h> #endif // QT_NO_XFIXES diff --git a/src/gui/kernel/qdesktopwidget_qpa.cpp b/src/gui/kernel/qdesktopwidget_qpa.cpp index cff05f5..6257a8b 100644 --- a/src/gui/kernel/qdesktopwidget_qpa.cpp +++ b/src/gui/kernel/qdesktopwidget_qpa.cpp @@ -51,6 +51,8 @@ QT_USE_NAMESPACE void QDesktopWidgetPrivate::updateScreenList() { + Q_Q(QDesktopWidget); + QList<QPlatformScreen *> screenList = QApplicationPrivate::platformIntegration()->screens(); int targetLength = screenList.length(); int currentLength = screens.length(); @@ -72,19 +74,15 @@ void QDesktopWidgetPrivate::updateScreenList() } QRegion virtualGeometry; - bool doVirtualGeometry = QApplicationPrivate::platformIntegration()->isVirtualDesktop(); // update the geometry of each screen widget for (int i = 0; i < screens.length(); i++) { QRect screenGeometry = screenList.at(i)->geometry(); screens.at(i)->setGeometry(screenGeometry); - if (doVirtualGeometry) - virtualGeometry += screenGeometry; + virtualGeometry += screenGeometry; } - virtualScreen.setGeometry(virtualGeometry.boundingRect()); - Q_Q(QDesktopWidget); - q->setGeometry(virtualScreen.geometry()); + q->setGeometry(virtualGeometry.boundingRect()); } QDesktopWidget::QDesktopWidget() @@ -118,8 +116,6 @@ int QDesktopWidget::numScreens() const QWidget *QDesktopWidget::screen(int screen) { Q_D(QDesktopWidget); - if (QApplicationPrivate::platformIntegration()->isVirtualDesktop()) - return &d->virtualScreen; if (screen < 0 || screen >= d->screens.length()) return d->screens.at(0); return d->screens.at(screen); diff --git a/src/gui/kernel/qdesktopwidget_qpa_p.h b/src/gui/kernel/qdesktopwidget_qpa_p.h index abee8a1..d6ed686 100644 --- a/src/gui/kernel/qdesktopwidget_qpa_p.h +++ b/src/gui/kernel/qdesktopwidget_qpa_p.h @@ -76,7 +76,6 @@ public: void updateScreenList(); QList<QDesktopScreenWidget *> screens; - QDesktopScreenWidget virtualScreen; }; #endif // QDESKTOPWIDGET_QPA_P_H diff --git a/src/gui/kernel/qevent.cpp b/src/gui/kernel/qevent.cpp index 277a5e8..807c385 100644 --- a/src/gui/kernel/qevent.cpp +++ b/src/gui/kernel/qevent.cpp @@ -4629,223 +4629,4 @@ const QGestureEventPrivate *QGestureEvent::d_func() const #endif // QT_NO_GESTURES -/*! - \class QScrollPrepareEvent - \since 4.8 - \ingroup events - - \brief The QScrollPrepareEvent class is send in preparation of a scrolling. - - The scroll prepare event is send before scrolling (usually by QScroller) is started. - The object receiving this event should set viewportSize, maxContentPos and contentPos. - It also should accept this event to indicate that scrolling should be started. - - It is not guaranteed that a QScrollEvent will be send after an acceepted - QScrollPrepareEvent, e.g. in a case where the maximum content position is (0,0). - - \sa QScrollEvent, QScroller -*/ - -/*! - Creates new QScrollPrepareEvent - The \a startPos is the position of a touch or mouse event that started the scrolling. -*/ -QScrollPrepareEvent::QScrollPrepareEvent(const QPointF &startPos) - : QEvent(QEvent::ScrollPrepare) -{ - d = reinterpret_cast<QEventPrivate *>(new QScrollPrepareEventPrivate()); - d_func()->startPos = startPos; -} - -/*! - Destroys QScrollEvent. -*/ -QScrollPrepareEvent::~QScrollPrepareEvent() -{ - delete reinterpret_cast<QScrollPrepareEventPrivate *>(d); -} - -/*! - Returns the position of the touch or mouse event that started the scrolling. -*/ -QPointF QScrollPrepareEvent::startPos() const -{ - return d_func()->startPos; -} - -/*! - Returns size of the area that is to be scrolled as set by setViewportSize - - \sa setViewportSize() -*/ -QSizeF QScrollPrepareEvent::viewportSize() const -{ - return d_func()->viewportSize; -} - -/*! - Returns the range of coordinates for the content as set by setContentPosRange(). -*/ -QRectF QScrollPrepareEvent::contentPosRange() const -{ - return d_func()->contentPosRange; -} - -/*! - Returns the current position of the content as set by setContentPos. -*/ -QPointF QScrollPrepareEvent::contentPos() const -{ - return d_func()->contentPos; -} - - -/*! - Sets the size of the area that is to be scrolled to \a size. - - \sa viewportSize() -*/ -void QScrollPrepareEvent::setViewportSize(const QSizeF &size) -{ - d_func()->viewportSize = size; -} - -/*! - Sets the range of content coordinates to \a rect. - - \sa contentPosRange() -*/ -void QScrollPrepareEvent::setContentPosRange(const QRectF &rect) -{ - d_func()->contentPosRange = rect; -} - -/*! - Sets the current content position to \a pos. - - \sa contentPos() -*/ -void QScrollPrepareEvent::setContentPos(const QPointF &pos) -{ - d_func()->contentPos = pos; -} - - -/*! - \internal -*/ -QScrollPrepareEventPrivate *QScrollPrepareEvent::d_func() -{ - return reinterpret_cast<QScrollPrepareEventPrivate *>(d); -} - -/*! - \internal -*/ -const QScrollPrepareEventPrivate *QScrollPrepareEvent::d_func() const -{ - return reinterpret_cast<const QScrollPrepareEventPrivate *>(d); -} - -/*! - \class QScrollEvent - \since 4.8 - \ingroup events - - \brief The QScrollEvent class is send when scrolling. - - The scroll event is send to indicate that the receiver should be scrolled. - Usually the receiver should be something visual like QWidget or QGraphicsObject. - - Some care should be taken that no conflicting QScrollEvents are sent from two - sources. Using QScroller::scrollTo is save however. - - \sa QScrollPrepareEvent, QScroller -*/ - -/*! - \enum QScrollEvent::ScrollState - - This enum describes the states a scroll event can have. - - \value ScrollStarted Set for the first scroll event of a scroll activity. - - \value ScrollUpdated Set for all but the first and the last scroll event of a scroll activity. - - \value ScrollFinished Set for the last scroll event of a scroll activity. - - \sa QScrollEvent::scrollState() -*/ - -/*! - Creates a new QScrollEvent - \a contentPos is the new content position, \a overshootDistance is the - new overshoot distance while \a scrollState indicates if this scroll - event is the first one, the last one or some event in between. -*/ -QScrollEvent::QScrollEvent(const QPointF &contentPos, const QPointF &overshootDistance, ScrollState scrollState) - : QEvent(QEvent::Scroll) -{ - d = reinterpret_cast<QEventPrivate *>(new QScrollEventPrivate()); - d_func()->contentPos = contentPos; - d_func()->overshoot= overshootDistance; - d_func()->state = scrollState; -} - -/*! - Destroys QScrollEvent. -*/ -QScrollEvent::~QScrollEvent() -{ - delete reinterpret_cast<QScrollEventPrivate *>(d); -} - -/*! - Returns the new scroll position. -*/ -QPointF QScrollEvent::contentPos() const -{ - return d_func()->contentPos; -} - -/*! - Returns the new overshoot distance. - See QScroller for an explanation of the term overshoot. - - \sa QScroller -*/ -QPointF QScrollEvent::overshootDistance() const -{ - return d_func()->overshoot; -} - -/*! - Returns the current scroll state as a combination of ScrollStateFlag values. - ScrollStarted (or ScrollFinished) will be set, if this scroll event is the first (or last) event in a scrolling activity. - Please note that both values can be set at the same time, if the activity consists of a single QScrollEvent. - All other scroll events in between will have their state set to ScrollUpdated. - - A widget could for example revert selections when scrolling is started and stopped. -*/ -QScrollEvent::ScrollState QScrollEvent::scrollState() const -{ - return d_func()->state; -} - -/*! - \internal -*/ -QScrollEventPrivate *QScrollEvent::d_func() -{ - return reinterpret_cast<QScrollEventPrivate *>(d); -} - -/*! - \internal -*/ -const QScrollEventPrivate *QScrollEvent::d_func() const -{ - return reinterpret_cast<const QScrollEventPrivate *>(d); -} - QT_END_NAMESPACE diff --git a/src/gui/kernel/qevent.h b/src/gui/kernel/qevent.h index 93c2bc5..830f037 100644 --- a/src/gui/kernel/qevent.h +++ b/src/gui/kernel/qevent.h @@ -889,52 +889,6 @@ private: }; #endif // QT_NO_GESTURES -class QScrollPrepareEventPrivate; -class Q_GUI_EXPORT QScrollPrepareEvent : public QEvent -{ -public: - QScrollPrepareEvent(const QPointF &startPos); - ~QScrollPrepareEvent(); - - QPointF startPos() const; - - QSizeF viewportSize() const; - QRectF contentPosRange() const; - QPointF contentPos() const; - - void setViewportSize(const QSizeF &size); - void setContentPosRange(const QRectF &rect); - void setContentPos(const QPointF &pos); - -private: - QScrollPrepareEventPrivate *d_func(); - const QScrollPrepareEventPrivate *d_func() const; -}; - - -class QScrollEventPrivate; -class Q_GUI_EXPORT QScrollEvent : public QEvent -{ -public: - enum ScrollState - { - ScrollStarted, - ScrollUpdated, - ScrollFinished - }; - - QScrollEvent(const QPointF &contentPos, const QPointF &overshoot, ScrollState scrollState); - ~QScrollEvent(); - - QPointF contentPos() const; - QPointF overshootDistance() const; - ScrollState scrollState() const; - -private: - QScrollEventPrivate *d_func(); - const QScrollEventPrivate *d_func() const; -}; - QT_END_NAMESPACE QT_END_HEADER diff --git a/src/gui/kernel/qevent_p.h b/src/gui/kernel/qevent_p.h index b79f372..36655e8 100644 --- a/src/gui/kernel/qevent_p.h +++ b/src/gui/kernel/qevent_p.h @@ -186,34 +186,6 @@ public: #endif }; - -class QScrollPrepareEventPrivate -{ -public: - inline QScrollPrepareEventPrivate() - : target(0) - { - } - - QObject* target; - QPointF startPos; - QSizeF viewportSize; - QRectF contentPosRange; - QPointF contentPos; -}; - -class QScrollEventPrivate -{ -public: - inline QScrollEventPrivate() - { - } - - QPointF contentPos; - QPointF overshoot; - QScrollEvent::ScrollState state; -}; - QT_END_NAMESPACE #endif // QEVENT_P_H diff --git a/src/gui/kernel/qgesturemanager.cpp b/src/gui/kernel/qgesturemanager.cpp index 5359fb3..7aa7dffd 100644 --- a/src/gui/kernel/qgesturemanager.cpp +++ b/src/gui/kernel/qgesturemanager.cpp @@ -566,7 +566,6 @@ void QGestureManager::getGestureTargets(const QSet<QGesture*> &gestures, = w->d_func()->gestureContext.find(type); if (it != w->d_func()->gestureContext.end()) { // i.e. 'w' listens to gesture 'type' - Qt::GestureFlags flags = it.value(); if (!(it.value() & Qt::DontStartGestureOnChildren) && w != widget) { // conflicting gesture! (*conflicts)[widget].append(gestures[widget]); diff --git a/src/gui/kernel/qplatformclipboard_qpa.cpp b/src/gui/kernel/qplatformclipboard_qpa.cpp index 957a4df..33d2afc 100644 --- a/src/gui/kernel/qplatformclipboard_qpa.cpp +++ b/src/gui/kernel/qplatformclipboard_qpa.cpp @@ -42,6 +42,8 @@ #ifndef QT_NO_CLIPBOARD +#include <QtGui/private/qapplication_p.h> + QT_BEGIN_NAMESPACE class QClipboardData @@ -100,6 +102,11 @@ bool QPlatformClipboard::supportsMode(QClipboard::Mode mode) const return mode == QClipboard::Clipboard; } +void QPlatformClipboard::emitChanged(QClipboard::Mode mode) +{ + QApplication::clipboard()->emitChanged(mode); +} + QT_END_NAMESPACE #endif //QT_NO_CLIPBOARD diff --git a/src/gui/kernel/qplatformclipboard_qpa.h b/src/gui/kernel/qplatformclipboard_qpa.h index 3381c06..5444a1f 100644 --- a/src/gui/kernel/qplatformclipboard_qpa.h +++ b/src/gui/kernel/qplatformclipboard_qpa.h @@ -62,6 +62,7 @@ public: virtual const QMimeData *mimeData(QClipboard::Mode mode = QClipboard::Clipboard ) const; virtual void setMimeData(QMimeData *data, QClipboard::Mode mode = QClipboard::Clipboard); virtual bool supportsMode(QClipboard::Mode mode) const; + void emitChanged(QClipboard::Mode mode); }; QT_END_NAMESPACE diff --git a/src/gui/kernel/qplatformintegration_qpa.cpp b/src/gui/kernel/qplatformintegration_qpa.cpp index d559c53..8ff12eb 100644 --- a/src/gui/kernel/qplatformintegration_qpa.cpp +++ b/src/gui/kernel/qplatformintegration_qpa.cpp @@ -214,6 +214,7 @@ QPlatformNativeInterface * QPlatformIntegration::nativeInterface() const bool QPlatformIntegration::hasCapability(Capability cap) const { + Q_UNUSED(cap); return false; } diff --git a/src/gui/kernel/qplatformwindow_qpa.cpp b/src/gui/kernel/qplatformwindow_qpa.cpp index 19bf7a9..f3654b6 100644 --- a/src/gui/kernel/qplatformwindow_qpa.cpp +++ b/src/gui/kernel/qplatformwindow_qpa.cpp @@ -150,7 +150,7 @@ void QPlatformWindow::setParent(const QPlatformWindow *parent) /*! Reimplement to set the window title to \a title */ -void QPlatformWindow::setWindowTitle(const QString &title) {} +void QPlatformWindow::setWindowTitle(const QString &) {} /*! Reimplement to be able to let Qt rais windows to the top of the desktop diff --git a/src/gui/kernel/qsessionmanager_qpa.cpp b/src/gui/kernel/qsessionmanager_qpa.cpp index ef532d7..68685b4 100644 --- a/src/gui/kernel/qsessionmanager_qpa.cpp +++ b/src/gui/kernel/qsessionmanager_qpa.cpp @@ -42,6 +42,8 @@ #include <qsessionmanager.h> #include <private/qobject_p.h> +#include <qapplication.h> + #ifndef QT_NO_SESSIONMANAGER QT_BEGIN_NAMESPACE diff --git a/src/gui/kernel/qsoftkeymanager_s60.cpp b/src/gui/kernel/qsoftkeymanager_s60.cpp index 79ed91a..71ae520 100644 --- a/src/gui/kernel/qsoftkeymanager_s60.cpp +++ b/src/gui/kernel/qsoftkeymanager_s60.cpp @@ -176,22 +176,27 @@ void QSoftKeyManagerPrivateS60::setNativeSoftkey(CEikButtonGroupContainer &cba, QPoint QSoftKeyManagerPrivateS60::softkeyIconPosition(int position, QSize sourceSize, QSize targetSize) { QPoint iconPosition(0,0); - switch( AknLayoutUtils::CbaLocation() ) - { - case AknLayoutUtils::EAknCbaLocationBottom: - // RSK must be moved to right, LSK in on correct position by default - if (position == RSK_POSITION) - iconPosition.setX(targetSize.width() - sourceSize.width()); - break; - case AknLayoutUtils::EAknCbaLocationRight: - case AknLayoutUtils::EAknCbaLocationLeft: - // Already in correct position - default: - break; - } - // Align horizontally to center - iconPosition.setY((targetSize.height() - sourceSize.height()) >> 1); + // Prior to S60 5.3 icons need to be properly positioned to buttons, but starting with 5.3 + // positioning is done on Avkon side. + if (QSysInfo::s60Version() < QSysInfo::SV_S60_5_3) { + switch (AknLayoutUtils::CbaLocation()) + { + case AknLayoutUtils::EAknCbaLocationBottom: + // RSK must be moved to right, LSK in on correct position by default + if (position == RSK_POSITION) + iconPosition.setX(targetSize.width() - sourceSize.width()); + break; + case AknLayoutUtils::EAknCbaLocationRight: + case AknLayoutUtils::EAknCbaLocationLeft: + // Already in correct position + default: + break; + } + + // Align horizontally to center + iconPosition.setY((targetSize.height() - sourceSize.height()) >> 1); + } return iconPosition; } @@ -278,12 +283,6 @@ bool QSoftKeyManagerPrivateS60::setSoftkeyImage(CEikButtonGroupContainer *cba, EikSoftkeyImage::SetImage(cba, *myimage, left); // Takes myimage ownership cbaHasImage[position] = true; ret = true; - } else { - // Restore softkey to text based - if (cbaHasImage[position]) { - EikSoftkeyImage::SetLabel(cba, left); - cbaHasImage[position] = false; - } } } return ret; @@ -294,7 +293,7 @@ bool QSoftKeyManagerPrivateS60::setSoftkey(CEikButtonGroupContainer &cba, { QAction *action = highestPrioritySoftkey(role); if (action) { - setSoftkeyImage(&cba, *action, position); + bool hasImage = setSoftkeyImage(&cba, *action, position); QString text = softkeyText(*action); TPtrC nativeText = qt_QString2TPtrC(text); int command = S60_COMMAND_START + position; @@ -303,6 +302,11 @@ bool QSoftKeyManagerPrivateS60::setSoftkey(CEikButtonGroupContainer &cba, command = softKeyCommandActions.value(action); #endif setNativeSoftkey(cba, position, command, nativeText); + if (!hasImage && cbaHasImage[position]) { + EikSoftkeyImage::SetLabel(&cba, (position == LSK_POSITION)); + cbaHasImage[position] = false; + } + const bool dimmed = !action->isEnabled() && !QSoftKeyManager::isForceEnabledInSofkeys(action); cba.DimCommand(command, dimmed); realSoftKeyActions.insert(command, action); @@ -313,7 +317,18 @@ bool QSoftKeyManagerPrivateS60::setSoftkey(CEikButtonGroupContainer &cba, bool QSoftKeyManagerPrivateS60::setLeftSoftkey(CEikButtonGroupContainer &cba) { - return setSoftkey(cba, QAction::PositiveSoftKey, LSK_POSITION); + if (!setSoftkey(cba, QAction::PositiveSoftKey, LSK_POSITION)) { + if (cbaHasImage[LSK_POSITION]) { + // Clear any residual icon if LSK has no action. A real softkey + // is needed for SetLabel command to work, so do a temporary dummy + setNativeSoftkey(cba, LSK_POSITION, EAknSoftkeyExit, KNullDesC); + EikSoftkeyImage::SetLabel(&cba, true); + setNativeSoftkey(cba, LSK_POSITION, EAknSoftkeyEmpty, KNullDesC); + cbaHasImage[LSK_POSITION] = false; + } + return false; + } + return true; } bool QSoftKeyManagerPrivateS60::setMiddleSoftkey(CEikButtonGroupContainer &cba) @@ -332,16 +347,26 @@ bool QSoftKeyManagerPrivateS60::setRightSoftkey(CEikButtonGroupContainer &cba) if (windowType != Qt::Dialog && windowType != Qt::Popup) { QString text(QSoftKeyManager::tr("Exit")); TPtrC nativeText = qt_QString2TPtrC(text); + setNativeSoftkey(cba, RSK_POSITION, EAknSoftkeyExit, nativeText); if (cbaHasImage[RSK_POSITION]) { EikSoftkeyImage::SetLabel(&cba, false); cbaHasImage[RSK_POSITION] = false; } - setNativeSoftkey(cba, RSK_POSITION, EAknSoftkeyExit, nativeText); cba.DimCommand(EAknSoftkeyExit, false); return true; + } else { + if (cbaHasImage[RSK_POSITION]) { + // Clear any residual icon if RSK has no action. A real softkey + // is needed for SetLabel command to work, so do a temporary dummy + setNativeSoftkey(cba, RSK_POSITION, EAknSoftkeyExit, KNullDesC); + EikSoftkeyImage::SetLabel(&cba, false); + setNativeSoftkey(cba, RSK_POSITION, EAknSoftkeyEmpty, KNullDesC); + cbaHasImage[RSK_POSITION] = false; + } + return false; } } - return false; + return true; } void QSoftKeyManagerPrivateS60::setSoftkeys(CEikButtonGroupContainer &cba) diff --git a/src/gui/kernel/qt_s60_p.h b/src/gui/kernel/qt_s60_p.h index 8aba53a..0023649 100644 --- a/src/gui/kernel/qt_s60_p.h +++ b/src/gui/kernel/qt_s60_p.h @@ -97,6 +97,10 @@ static const int qt_symbian_max_screens = 4; //this macro exists because EColor16MAP enum value doesn't exist in Symbian OS 9.2 #define Q_SYMBIAN_ECOLOR16MAP TDisplayMode(13) +class QSymbianTypeFaceExtras; +typedef QHash<QString, const QSymbianTypeFaceExtras *> QSymbianTypeFaceExtrasHash; +typedef void (*QThreadLocalReleaseFunc)(); + class Q_AUTOTEST_EXPORT QS60ThreadLocalData { public: @@ -105,6 +109,8 @@ public: bool usingCONEinstances; RWsSession wsSession; CWsScreenDevice *screenDevice; + QSymbianTypeFaceExtrasHash fontData; + QVector<QThreadLocalReleaseFunc> releaseFuncs; }; class QS60Data @@ -153,6 +159,8 @@ public: int menuBeingConstructed : 1; int orientationSet : 1; int partial_keyboard : 1; + int partial_keyboardAutoTranslation : 1; + int partialKeyboardOpen : 1; QApplication::QS60MainApplicationFactory s60ApplicationFactory; // typedef'ed pointer type QPointer<QWidget> splitViewLastWidget; @@ -175,6 +183,8 @@ public: inline CWsScreenDevice* screenDevice(const QWidget *widget); inline CWsScreenDevice* screenDevice(int screenNumber); static inline int screenNumberForWidget(const QWidget *widget); + inline QSymbianTypeFaceExtrasHash& fontData(); + inline void addThreadLocalReleaseFunc(QThreadLocalReleaseFunc func); static inline CCoeAppUi* appUi(); static inline CEikMenuBar* menuBar(); #ifdef Q_WS_S60 @@ -291,6 +301,7 @@ private: void translateAdvancedPointerEvent(const TAdvancedPointerEvent *event); #endif bool isSplitViewWidget(QWidget *widget); + bool hasFocusedAndVisibleChild(QWidget *parentWidget); public: void handleClientAreaChange(); @@ -340,6 +351,8 @@ inline QS60Data::QS60Data() menuBeingConstructed(0), orientationSet(0), partial_keyboard(0), + partial_keyboardAutoTranslation(1), + partialKeyboardOpen(0), s60ApplicationFactory(0) #ifdef Q_OS_SYMBIAN ,s60InstalledTrapHandler(0) @@ -470,6 +483,24 @@ inline int QS60Data::screenNumberForWidget(const QWidget *widget) return qt_widget_private(const_cast<QWidget *>(w))->symbianScreenNumber; } +inline QSymbianTypeFaceExtrasHash& QS60Data::fontData() +{ + if (!tls.hasLocalData()) { + tls.setLocalData(new QS60ThreadLocalData); + } + return tls.localData()->fontData; +} + +inline void QS60Data::addThreadLocalReleaseFunc(QThreadLocalReleaseFunc func) +{ + if (!tls.hasLocalData()) { + tls.setLocalData(new QS60ThreadLocalData); + } + QS60ThreadLocalData *data = tls.localData(); + if (!data->releaseFuncs.contains(func)) + data->releaseFuncs.append(func); +} + inline CCoeAppUi* QS60Data::appUi() { return CCoeEnv::Static()-> AppUi(); diff --git a/src/gui/kernel/qt_x11_p.h b/src/gui/kernel/qt_x11_p.h index 69079cf..8ab129c 100644 --- a/src/gui/kernel/qt_x11_p.h +++ b/src/gui/kernel/qt_x11_p.h @@ -226,7 +226,6 @@ typedef void (*PtrXRRSelectInput)(Display *, Window, int); typedef int (*PtrXRRUpdateConfiguration)(XEvent *); typedef int (*PtrXRRRootToScreen)(Display *, Window); typedef Bool (*PtrXRRQueryExtension)(Display *, int *, int *); -typedef XRRScreenSize *(*PtrXRRSizes)(Display *, int, int *); #endif // QT_NO_XRANDR #ifndef QT_NO_XINPUT @@ -711,7 +710,6 @@ struct QX11Data PtrXRRUpdateConfiguration ptrXRRUpdateConfiguration; PtrXRRRootToScreen ptrXRRRootToScreen; PtrXRRQueryExtension ptrXRRQueryExtension; - PtrXRRSizes ptrXRRSizes; #endif // QT_NO_XRANDR }; diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index c5ea239..9556169 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -299,6 +299,7 @@ QWidgetPrivate::QWidgetPrivate(int version) #ifndef QT_NO_IM , inheritsInputMethodHints(0) #endif + , inSetParent(0) #if defined(Q_WS_X11) , picture(0) #elif defined(Q_WS_WIN) @@ -612,7 +613,7 @@ void QWidget::setAutoFillBackground(bool enabled) \brief The QWidget class is the base class of all user interface objects. \ingroup basicwidgets - + The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a @@ -1389,16 +1390,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f) QApplication::postEvent(q, new QEvent(QEvent::PolishRequest)); extraPaintEngine = 0; - -#ifdef QT_MAC_USE_COCOA - // If we add a child to the unified toolbar, we have to redirect the painting. - if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) { - if (parentWidget->d_func()->unifiedSurface) { - QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor; - parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset); - } - } -#endif // QT_MAC_USE_COCOA } @@ -1588,6 +1579,7 @@ QWidget::~QWidget() // delete layout while we still are a valid widget delete d->layout; + d->layout = 0; // Remove myself from focus list Q_ASSERT(d->focus_next->d_func()->focus_prev == this); @@ -2598,6 +2590,22 @@ WId QWidget::effectiveWinId() const if (id || !testAttribute(Qt::WA_WState_Created)) return id; QWidget *realParent = nativeParentWidget(); + if (!realParent && d_func()->inSetParent) { + // In transitional state. This is really just a workaround. The real problem + // is that QWidgetPrivate::setParent_sys (platform specific code) first sets + // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created + // attribute to false. The correct way is to do it the other way around, and + // in that case the Qt::WA_WState_Created logic above will kick in and + // return 0 whenever the widget is in a transitional state. However, changing + // the original logic for all platforms is far more intrusive and might + // break existing applications. + // Note: The widget can only be in a transitional state when changing its + // parent -- everything else is an internal error -- hence explicitly checking + // against 'inSetParent' rather than doing an unconditional return whenever + // 'realParent' is 0 (which may cause strange artifacts and headache later). + return 0; + } + // This widget *must* have a native parent widget. Q_ASSERT(realParent); Q_ASSERT(realParent->internalWinId()); return realParent->internalWinId(); @@ -10110,6 +10118,7 @@ void QWidget::setParent(QWidget *parent) void QWidget::setParent(QWidget *parent, Qt::WindowFlags f) { Q_D(QWidget); + d->inSetParent = true; bool resized = testAttribute(Qt::WA_Resized); bool wasCreated = testAttribute(Qt::WA_WState_Created); QWidget *oldtlw = window(); @@ -10270,6 +10279,8 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f) ancestorProxy->d_func()->embedSubWindow(this); } #endif + + d->inSetParent = false; } /*! diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm index 354f05b..468de22 100644 --- a/src/gui/kernel/qwidget_mac.mm +++ b/src/gui/kernel/qwidget_mac.mm @@ -2733,7 +2733,7 @@ QWidget::macCGHandle() const return handle(); } -void qt_mac_repaintParentUnderAlienWidget(QWidget *alienWidget) +void qt_mac_updateParentUnderAlienWidget(QWidget *alienWidget) { QWidget *nativeParent = alienWidget->nativeParentWidget(); if (!nativeParent) @@ -2741,7 +2741,7 @@ void qt_mac_repaintParentUnderAlienWidget(QWidget *alienWidget) QPoint globalPos = alienWidget->mapToGlobal(QPoint(0, 0)); QRect dirtyRect = QRect(nativeParent->mapFromGlobal(globalPos), alienWidget->size()); - nativeParent->repaint(dirtyRect); + nativeParent->update(dirtyRect); } void QWidget::destroy(bool destroyWindow, bool destroySubWindows) @@ -2752,7 +2752,7 @@ void QWidget::destroy(bool destroyWindow, bool destroySubWindows) if (!isWindow() && parentWidget()) parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry())); if (!internalWinId()) - qt_mac_repaintParentUnderAlienWidget(this); + qt_mac_updateParentUnderAlienWidget(this); d->deactivateWidgetCleanup(); qt_mac_event_release(this); if(testAttribute(Qt::WA_WState_Created)) { @@ -3032,6 +3032,16 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f) q->setAttribute(Qt::WA_WState_Hidden); q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden); +#ifdef QT_MAC_USE_COCOA + // If we add a child to the unified toolbar, we have to redirect the painting. + if (parent && parent->d_func() && parent->d_func()->isInUnifiedToolbar) { + if (parent->d_func()->unifiedSurface) { + QWidget *toolbar = parent->d_func()->toolbar_ancestor; + parent->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset); + } + } +#endif // QT_MAC_USE_COCOA + if (wasCreated) { transferChildren(); #ifndef QT_MAC_USE_COCOA @@ -3526,8 +3536,8 @@ void QWidgetPrivate::show_sys() // INVARIANT: q is native. Just show the view: [view setHidden:NO]; } else { - // INVARIANT: q is alien. Repaint q instead: - q->repaint(); + // INVARIANT: q is alien. Update q instead: + q->update(); } #endif } @@ -3683,7 +3693,7 @@ void QWidgetPrivate::hide_sys() [view setHidden:YES]; } else { // INVARIANT: q is alien. Repaint where q is placed instead: - qt_mac_repaintParentUnderAlienWidget(q); + qt_mac_updateParentUnderAlienWidget(q); } #endif } diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h index 919f8bc..acf1860 100644 --- a/src/gui/kernel/qwidget_p.h +++ b/src/gui/kernel/qwidget_p.h @@ -232,6 +232,7 @@ struct QTLWExtra { #elif defined(Q_OS_SYMBIAN) uint inExpose : 1; // Prevents drawing recursion uint nativeWindowTransparencyEnabled : 1; // Tracks native window transparency + uint forcedToRaster : 1; #elif defined(Q_WS_QPA) QPlatformWindow *platformWindow; QPlatformWindowFormat platformWindowFormat; @@ -770,6 +771,7 @@ public: #ifndef QT_NO_IM uint inheritsInputMethodHints : 1; #endif + uint inSetParent : 1; // *************************** Platform specific ************************************ #if defined(Q_WS_X11) // <----------------------------------------------------------- X11 diff --git a/src/gui/kernel/qwidget_s60.cpp b/src/gui/kernel/qwidget_s60.cpp index e28a75a..c011cf1 100644 --- a/src/gui/kernel/qwidget_s60.cpp +++ b/src/gui/kernel/qwidget_s60.cpp @@ -235,11 +235,22 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove) QSize oldSize(q->size()); QRect oldGeom(data.crect); + bool checkExtra = true; + if (q->isWindow() && (data.window_state & (Qt::WindowFullScreen | Qt::WindowMaximized))) { + // Do not allow fullscreen/maximized windows to expand beyond client rect + TRect r = static_cast<CEikAppUi*>(S60->appUi())->ClientRect(); + w = qMin(w, r.Width()); + h = qMin(h, r.Height()); + + if (w == r.Width() && h == r.Height()) + checkExtra = false; + } + // Lose maximized status if deliberate resize if (w != oldSize.width() || h != oldSize.height()) data.window_state &= ~Qt::WindowMaximized; - if (extra) { // any size restrictions? + if (checkExtra && extra) { // any size restrictions? w = qMin(w,extra->maxw); h = qMin(h,extra->maxh); w = qMax(w,extra->minw); @@ -567,6 +578,11 @@ void QWidgetPrivate::show_sys() if (isFullscreen) { const bool cbaVisible = S60->buttonGroupContainer() && S60->buttonGroupContainer()->IsVisible(); S60->setStatusPaneAndButtonGroupVisibility(false, cbaVisible); + if (cbaVisible) { + // Fix window dimensions as without screen furniture they will have + // defaulted to full screen dimensions initially. + id->handleClientAreaChange(); + } } } } @@ -781,7 +797,7 @@ void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f) adjustFlags(data.window_flags, q); // keep compatibility with previous versions, we need to preserve the created state // (but we recreate the winId for the widget being reparented, again for compatibility) - if (wasCreated || (!q->isWindow() && parent->testAttribute(Qt::WA_WState_Created))) + if (wasCreated || (!q->isWindow() && parent && parent->testAttribute(Qt::WA_WState_Created))) createWinId(); if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden) q->setAttribute(Qt::WA_WState_Hidden); @@ -824,7 +840,8 @@ void QWidgetPrivate::s60UpdateIsOpaque() RWindow *const window = static_cast<RWindow *>(q->effectiveWinId()->DrawableWindow()); #ifdef Q_SYMBIAN_SEMITRANSPARENT_BG_SURFACE - if (QApplicationPrivate::instance()->useTranslucentEGLSurfaces) { + if (QApplicationPrivate::instance()->useTranslucentEGLSurfaces + && !extra->topextra->forcedToRaster) { window->SetSurfaceTransparency(!isOpaque); extra->topextra->nativeWindowTransparencyEnabled = !isOpaque; return; @@ -1008,6 +1025,7 @@ void QWidgetPrivate::createTLSysExtra() { extra->topextra->inExpose = 0; extra->topextra->nativeWindowTransparencyEnabled = 0; + extra->topextra->forcedToRaster = 0; } void QWidgetPrivate::deleteTLSysExtra() diff --git a/src/gui/kernel/qwidget_x11.cpp b/src/gui/kernel/qwidget_x11.cpp index 5ece7d6..3eec5c7 100644 --- a/src/gui/kernel/qwidget_x11.cpp +++ b/src/gui/kernel/qwidget_x11.cpp @@ -486,8 +486,6 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO bool topLevel = (flags & Qt::Window); bool popup = (type == Qt::Popup); - bool dialog = (type == Qt::Dialog - || type == Qt::Sheet); bool desktop = (type == Qt::Desktop); bool tool = (type == Qt::Tool || type == Qt::SplashScreen || type == Qt::ToolTip || type == Qt::Drawer); @@ -553,7 +551,7 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO int sh = DisplayHeight(dpy,scr); if (desktop) { // desktop widget - dialog = popup = false; // force these flags off + popup = false; // force these flags off data.crect.setRect(0, 0, sw, sh); } else if (topLevel && !q->testAttribute(Qt::WA_Resized)) { QDesktopWidget *desktopWidget = qApp->desktop(); @@ -954,8 +952,13 @@ static void qt_x11_recreateWidget(QWidget *widget) // recreate their GL context, which in turn causes them to choose // their visual again. Now that WA_TranslucentBackground is set, // QGLContext::chooseVisual will select an ARGB visual. - QEvent e(QEvent::ParentChange); - QApplication::sendEvent(widget, &e); + + // QGLWidget expects a ParentAboutToChange to be sent first + QEvent aboutToChangeEvent(QEvent::ParentAboutToChange); + QApplication::sendEvent(widget, &aboutToChangeEvent); + + QEvent parentChangeEvent(QEvent::ParentChange); + QApplication::sendEvent(widget, &parentChangeEvent); } else { // For regular widgets, reparent them with their parent which // also triggers a recreation of the native window diff --git a/src/gui/painting/painting.pri b/src/gui/painting/painting.pri index 65e7af4..f1496b1 100644 --- a/src/gui/painting/painting.pri +++ b/src/gui/painting/painting.pri @@ -9,6 +9,7 @@ HEADERS += \ painting/qdrawutil.h \ painting/qemulationpaintengine_p.h \ painting/qgraphicssystem_p.h \ + painting/qgraphicssystemex_p.h \ painting/qmatrix.h \ painting/qmemrotate_p.h \ painting/qoutlinemapper_p.h \ @@ -249,8 +250,10 @@ embedded { symbian { HEADERS += painting/qwindowsurface_s60_p.h \ - painting/qdrawhelper_arm_simd_p.h - SOURCES += painting/qwindowsurface_s60.cpp + painting/qdrawhelper_arm_simd_p.h \ + painting/qgraphicssystemex_symbian_p.h + SOURCES += painting/qwindowsurface_s60.cpp \ + painting/qgraphicssystemex_symbian.cpp armccIfdefBlock = \ "$${LITERAL_HASH}if defined(ARMV6)" \ "MACRO QT_HAVE_ARM_SIMD" \ diff --git a/src/gui/painting/qbrush.cpp b/src/gui/painting/qbrush.cpp index bf5764a..3ff7eb8 100644 --- a/src/gui/painting/qbrush.cpp +++ b/src/gui/painting/qbrush.cpp @@ -840,6 +840,22 @@ const QGradient *QBrush::gradient() const return 0; } +Q_GUI_EXPORT bool qt_isExtendedRadialGradient(const QBrush &brush) +{ + if (brush.style() == Qt::RadialGradientPattern) { + const QGradient *g = brush.gradient(); + const QRadialGradient *rg = static_cast<const QRadialGradient *>(g); + + if (!qFuzzyIsNull(rg->focalRadius())) + return true; + + QPointF delta = rg->focalPoint() - rg->center(); + if (delta.x() * delta.x() + delta.y() * delta.y() > rg->radius() * rg->radius()) + return true; + } + + return false; +} /*! Returns true if the brush is fully opaque otherwise false. A brush @@ -849,6 +865,7 @@ const QGradient *QBrush::gradient() const \i The alpha component of the color() is 255. \i Its texture() does not have an alpha channel and is not a QBitmap. \i The colors in the gradient() all have an alpha component that is 255. + \i It is an extended radial gradient. \endlist */ @@ -860,6 +877,9 @@ bool QBrush::isOpaque() const if (d->style == Qt::SolidPattern) return opaqueColor; + if (qt_isExtendedRadialGradient(*this)) + return false; + if (d->style == Qt::LinearGradientPattern || d->style == Qt::RadialGradientPattern || d->style == Qt::ConicalGradientPattern) { @@ -1209,8 +1229,10 @@ QDataStream &operator>>(QDataStream &s, QBrush &b) \list \o \e Linear gradients interpolate colors between start and end points. - \o \e Radial gradients interpolate colors between a focal point and end - points on a circle surrounding it. + \o \e Simple radial gradients interpolate colors between a focal point + and end points on a circle surrounding it. + \o \e Extended radial gradients interpolate colors between a center and + a focal circle. \o \e Conical gradients interpolate colors around a center point. \endlist @@ -1506,8 +1528,6 @@ void QGradient::setInterpolationMode(InterpolationMode mode) dummy = p; } -#undef Q_DUMMY_ACCESSOR - /*! \fn bool QGradient::operator!=(const QGradient &gradient) const \since 4.2 @@ -1541,7 +1561,7 @@ bool QGradient::operator==(const QGradient &gradient) const || m_data.radial.cy != gradient.m_data.radial.cy || m_data.radial.fx != gradient.m_data.radial.fx || m_data.radial.fy != gradient.m_data.radial.fy - || m_data.radial.radius != gradient.m_data.radial.radius) + || m_data.radial.cradius != gradient.m_data.radial.cradius) return false; } else { // m_type == ConicalGradient if (m_data.conical.cx != gradient.m_data.conical.cx @@ -1747,10 +1767,17 @@ void QLinearGradient::setFinalStop(const QPointF &stop) \brief The QRadialGradient class is used in combination with QBrush to specify a radial gradient brush. - Radial gradients interpolate colors between a focal point and end - points on a circle surrounding it. Outside the end points the - gradient is either padded, reflected or repeated depending on the - currently set \l {QGradient::Spread}{spread} method: + Qt supports both simple and extended radial gradients. + + Simple radial gradients interpolate colors between a focal point and end + points on a circle surrounding it. Extended radial gradients interpolate + colors between a focal circle and a center circle. Points outside the cone + defined by the two circles will be transparent. For simple radial gradients + the focal point is adjusted to lie inside the center circle, whereas the + focal point can have any position in an extended radial gradient. + + Outside the end points the gradient is either padded, reflected or repeated + depending on the currently set \l {QGradient::Spread}{spread} method: \table \row @@ -1795,9 +1822,14 @@ static QPointF qt_radial_gradient_adapt_focal_point(const QPointF ¢er, } /*! - Constructs a radial gradient with the given \a center, \a + Constructs a simple radial gradient with the given \a center, \a radius and \a focalPoint. + \note If the given focal point is outside the circle defined by the + center (\a cx, \a cy) and the \a radius it will be re-adjusted to + the intersection between the line from the center to the focal point + and the circle. + \sa QGradient::setColorAt(), QGradient::setStops() */ @@ -1807,7 +1839,7 @@ QRadialGradient::QRadialGradient(const QPointF ¢er, qreal radius, const QPoi m_spread = PadSpread; m_data.radial.cx = center.x(); m_data.radial.cy = center.y(); - m_data.radial.radius = radius; + m_data.radial.cradius = radius; QPointF adapted_focal = qt_radial_gradient_adapt_focal_point(center, radius, focalPoint); m_data.radial.fx = adapted_focal.x(); @@ -1815,7 +1847,7 @@ QRadialGradient::QRadialGradient(const QPointF ¢er, qreal radius, const QPoi } /*! - Constructs a radial gradient with the given \a center, \a + Constructs a simple radial gradient with the given \a center, \a radius and the focal point in the circle center. \sa QGradient::setColorAt(), QGradient::setStops() @@ -1826,16 +1858,21 @@ QRadialGradient::QRadialGradient(const QPointF ¢er, qreal radius) m_spread = PadSpread; m_data.radial.cx = center.x(); m_data.radial.cy = center.y(); - m_data.radial.radius = radius; + m_data.radial.cradius = radius; m_data.radial.fx = center.x(); m_data.radial.fy = center.y(); } /*! - Constructs a radial gradient with the given center (\a cx, \a cy), + Constructs a simple radial gradient with the given center (\a cx, \a cy), \a radius and focal point (\a fx, \a fy). + \note If the given focal point is outside the circle defined by the + center (\a cx, \a cy) and the \a radius it will be re-adjusted to + the intersection between the line from the center to the focal point + and the circle. + \sa QGradient::setColorAt(), QGradient::setStops() */ @@ -1845,7 +1882,7 @@ QRadialGradient::QRadialGradient(qreal cx, qreal cy, qreal radius, qreal fx, qre m_spread = PadSpread; m_data.radial.cx = cx; m_data.radial.cy = cy; - m_data.radial.radius = radius; + m_data.radial.cradius = radius; QPointF adapted_focal = qt_radial_gradient_adapt_focal_point(QPointF(cx, cy), radius, @@ -1856,7 +1893,7 @@ QRadialGradient::QRadialGradient(qreal cx, qreal cy, qreal radius, qreal fx, qre } /*! - Constructs a radial gradient with the center at (\a cx, \a cy) and the + Constructs a simple radial gradient with the center at (\a cx, \a cy) and the specified \a radius. The focal point lies at the center of the circle. \sa QGradient::setColorAt(), QGradient::setStops() @@ -1867,14 +1904,14 @@ QRadialGradient::QRadialGradient(qreal cx, qreal cy, qreal radius) m_spread = PadSpread; m_data.radial.cx = cx; m_data.radial.cy = cy; - m_data.radial.radius = radius; + m_data.radial.cradius = radius; m_data.radial.fx = cx; m_data.radial.fy = cy; } /*! - Constructs a radial gradient with the center and focal point at + Constructs a simple radial gradient with the center and focal point at (0, 0) with a radius of 1. */ QRadialGradient::QRadialGradient() @@ -1883,11 +1920,51 @@ QRadialGradient::QRadialGradient() m_spread = PadSpread; m_data.radial.cx = 0; m_data.radial.cy = 0; - m_data.radial.radius = 1; + m_data.radial.cradius = 1; m_data.radial.fx = 0; m_data.radial.fy = 0; } +/*! + \since 4.8 + + Constructs an extended radial gradient with the given \a center, \a + centerRadius, \a focalPoint, and \a focalRadius. +*/ +QRadialGradient::QRadialGradient(const QPointF ¢er, qreal centerRadius, const QPointF &focalPoint, qreal focalRadius) +{ + m_type = RadialGradient; + m_spread = PadSpread; + m_data.radial.cx = center.x(); + m_data.radial.cy = center.y(); + m_data.radial.cradius = centerRadius; + + m_data.radial.fx = focalPoint.x(); + m_data.radial.fy = focalPoint.y(); + setFocalRadius(focalRadius); +} + +/*! + \since 4.8 + + Constructs an extended radial gradient with the given \a center, \a + centerRadius, \a focalPoint, and \a focalRadius. + Constructs a radial gradient with the given center (\a cx, \a cy), + center radius \a centerRadius, focal point (\a fx, \a fy), and + focal radius \a focalRadius. +*/ +QRadialGradient::QRadialGradient(qreal cx, qreal cy, qreal centerRadius, qreal fx, qreal fy, qreal focalRadius) +{ + m_type = RadialGradient; + m_spread = PadSpread; + m_data.radial.cx = cx; + m_data.radial.cy = cy; + m_data.radial.cradius = centerRadius; + + m_data.radial.fx = fx; + m_data.radial.fy = fy; + setFocalRadius(focalRadius); +} /*! Returns the center of this radial gradient in logical coordinates. @@ -1932,13 +2009,15 @@ void QRadialGradient::setCenter(const QPointF ¢er) /*! Returns the radius of this radial gradient in logical coordinates. + Equivalent to centerRadius() + \sa QGradient::stops() */ qreal QRadialGradient::radius() const { Q_ASSERT(m_type == RadialGradient); - return m_data.radial.radius; + return m_data.radial.cradius; } @@ -1947,13 +2026,81 @@ qreal QRadialGradient::radius() const Sets the radius of this radial gradient in logical coordinates to \a radius + + Equivalent to setCenterRadius() */ void QRadialGradient::setRadius(qreal radius) { Q_ASSERT(m_type == RadialGradient); - m_data.radial.radius = radius; + m_data.radial.cradius = radius; +} + +/*! + \since 4.8 + + Returns the center radius of this radial gradient in logical + coordinates. + + \sa QGradient::stops() +*/ +qreal QRadialGradient::centerRadius() const +{ + Q_ASSERT(m_type == RadialGradient); + return m_data.radial.cradius; +} + +/* + \since 4.8 + + Sets the center radius of this radial gradient in logical coordinates + to \a radius +*/ +void QRadialGradient::setCenterRadius(qreal radius) +{ + Q_ASSERT(m_type == RadialGradient); + m_data.radial.cradius = radius; +} + +/*! + \since 4.8 + + Returns the focal radius of this radial gradient in logical + coordinates. + + \sa QGradient::stops() +*/ +qreal QRadialGradient::focalRadius() const +{ + Q_ASSERT(m_type == RadialGradient); + Q_DUMMY_ACCESSOR + + // mask away low three bits + union { float f; quint32 i; } u; + u.i = i & ~0x07; + return u.f; } +/* + \since 4.8 + + Sets the focal radius of this radial gradient in logical coordinates + to \a radius +*/ +void QRadialGradient::setFocalRadius(qreal radius) +{ + Q_ASSERT(m_type == RadialGradient); + Q_DUMMY_ACCESSOR + + // Since there's no QGradientData, we only have the dummy void * to + // store additional data in. The three lowest bits are already + // taken, thus we cut the three lowest bits from the significand + // and store the radius as a float. + union { float f; quint32 i; } u; + u.f = float(radius); + // add 0x04 to round up when we drop the three lowest bits + i |= (u.i + 0x04) & ~0x07; + dummy = p; +} /*! Returns the focal point of this radial gradient in logical @@ -2193,4 +2340,6 @@ void QConicalGradient::setAngle(qreal angle) \sa setTransform() */ +#undef Q_DUMMY_ACCESSOR + QT_END_NAMESPACE diff --git a/src/gui/painting/qbrush.h b/src/gui/painting/qbrush.h index 8b31319..d914c8c 100644 --- a/src/gui/painting/qbrush.h +++ b/src/gui/painting/qbrush.h @@ -255,6 +255,7 @@ private: friend class QLinearGradient; friend class QRadialGradient; friend class QConicalGradient; + friend class QBrush; Type m_type; Spread m_spread; @@ -264,7 +265,7 @@ private: qreal x1, y1, x2, y2; } linear; struct { - qreal cx, cy, fx, fy, radius; + qreal cx, cy, fx, fy, cradius; } radial; struct { qreal cx, cy, angle; @@ -303,6 +304,9 @@ public: QRadialGradient(const QPointF ¢er, qreal radius); QRadialGradient(qreal cx, qreal cy, qreal radius); + QRadialGradient(const QPointF ¢er, qreal centerRadius, const QPointF &focalPoint, qreal focalRadius); + QRadialGradient(qreal cx, qreal cy, qreal centerRadius, qreal fx, qreal fy, qreal focalRadius); + QPointF center() const; void setCenter(const QPointF ¢er); inline void setCenter(qreal x, qreal y) { setCenter(QPointF(x, y)); } @@ -313,6 +317,12 @@ public: qreal radius() const; void setRadius(qreal radius); + + qreal centerRadius() const; + void setCenterRadius(qreal radius); + + qreal focalRadius() const; + void setFocalRadius(qreal radius); }; diff --git a/src/gui/painting/qcolor.cpp b/src/gui/painting/qcolor.cpp index ff6c24e..cd87d21 100644 --- a/src/gui/painting/qcolor.cpp +++ b/src/gui/painting/qcolor.cpp @@ -532,8 +532,7 @@ QString QColor::name() const void QColor::setNamedColor(const QString &name) { - if (!setColorFromString(name)) - qWarning("QColor::setNamedColor: Unknown color name '%s'", name.toLatin1().constData()); + setColorFromString(name); } /*! diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index 5e75e4a..360292c 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -75,43 +75,9 @@ enum { fixed_scale = 1 << 16, half_point = 1 << 15 }; -static const int buffer_size = 2048; - -struct LinearGradientValues -{ - qreal dx; - qreal dy; - qreal l; - qreal off; -}; - -struct RadialGradientValues -{ - qreal dx; - qreal dy; - qreal a; -}; - -struct Operator; -typedef uint* (QT_FASTCALL *DestFetchProc)(uint *buffer, QRasterBuffer *rasterBuffer, int x, int y, int length); -typedef void (QT_FASTCALL *DestStoreProc)(QRasterBuffer *rasterBuffer, int x, int y, const uint *buffer, int length); -typedef const uint* (QT_FASTCALL *SourceFetchProc)(uint *buffer, const Operator *o, const QSpanData *data, int y, int x, int length); - -struct Operator -{ - QPainter::CompositionMode mode; - DestFetchProc dest_fetch; - DestStoreProc dest_store; - SourceFetchProc src_fetch; - CompositionFunctionSolid funcSolid; - CompositionFunction func; - union { - LinearGradientValues linear; - RadialGradientValues radial; -// TextureValues texture; - }; -}; +// must be multiple of 4 for easier SIMD implementations +static const int buffer_size = 2048; /* Destination fetch. This is simple as we don't have to do bounds checks or @@ -1346,64 +1312,13 @@ static const SourceFetchProc sourceFetch[NBlendTypes][QImage::NImageFormats] = { }, }; - -static inline uint qt_gradient_pixel(const QGradientData *data, qreal pos) -{ - int ipos = int(pos * (GRADIENT_STOPTABLE_SIZE - 1) + qreal(0.5)); - - // calculate the actual offset. - if (ipos < 0 || ipos >= GRADIENT_STOPTABLE_SIZE) { - if (data->spread == QGradient::RepeatSpread) { - ipos = ipos % GRADIENT_STOPTABLE_SIZE; - ipos = ipos < 0 ? GRADIENT_STOPTABLE_SIZE + ipos : ipos; - - } else if (data->spread == QGradient::ReflectSpread) { - const int limit = GRADIENT_STOPTABLE_SIZE * 2 - 1; - ipos = ipos % limit; - ipos = ipos < 0 ? limit + ipos : ipos; - ipos = ipos >= GRADIENT_STOPTABLE_SIZE ? limit - ipos : ipos; - - } else { - if (ipos < 0) ipos = 0; - else if (ipos >= GRADIENT_STOPTABLE_SIZE) ipos = GRADIENT_STOPTABLE_SIZE-1; - } - } - - Q_ASSERT(ipos >= 0); - Q_ASSERT(ipos < GRADIENT_STOPTABLE_SIZE); - - return data->colorTable[ipos]; -} - #define FIXPT_BITS 8 #define FIXPT_SIZE (1<<FIXPT_BITS) static uint qt_gradient_pixel_fixed(const QGradientData *data, int fixed_pos) { int ipos = (fixed_pos + (FIXPT_SIZE / 2)) >> FIXPT_BITS; - - // calculate the actual offset. - if (ipos < 0 || ipos >= GRADIENT_STOPTABLE_SIZE) { - if (data->spread == QGradient::RepeatSpread) { - ipos = ipos % GRADIENT_STOPTABLE_SIZE; - ipos = ipos < 0 ? GRADIENT_STOPTABLE_SIZE + ipos : ipos; - - } else if (data->spread == QGradient::ReflectSpread) { - const int limit = GRADIENT_STOPTABLE_SIZE * 2 - 1; - ipos = ipos % limit; - ipos = ipos < 0 ? limit + ipos : ipos; - ipos = ipos >= GRADIENT_STOPTABLE_SIZE ? limit - ipos : ipos; - - } else { - if (ipos < 0) ipos = 0; - else if (ipos >= GRADIENT_STOPTABLE_SIZE) ipos = GRADIENT_STOPTABLE_SIZE-1; - } - } - - Q_ASSERT(ipos >= 0); - Q_ASSERT(ipos < GRADIENT_STOPTABLE_SIZE); - - return data->colorTable[ipos]; + return data->colorTable[qt_gradient_clamp(data, ipos)]; } static void QT_FASTCALL getLinearGradientValues(LinearGradientValues *v, const QSpanData *data) @@ -1419,8 +1334,8 @@ static void QT_FASTCALL getLinearGradientValues(LinearGradientValues *v, const Q } } -static const uint * QT_FASTCALL fetchLinearGradient(uint *buffer, const Operator *op, const QSpanData *data, - int y, int x, int length) +static const uint * QT_FASTCALL qt_fetch_linear_gradient(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length) { const uint *b = buffer; qreal t, inc; @@ -1487,110 +1402,65 @@ static const uint * QT_FASTCALL fetchLinearGradient(uint *buffer, const Operator return b; } -static inline qreal determinant(qreal a, qreal b, qreal c) -{ - return (b * b) - (4 * a * c); -} - -// function to evaluate real roots -static inline qreal realRoots(qreal a, qreal b, qreal detSqrt) -{ - return (-b + detSqrt)/(2 * a); -} - -static inline qreal qSafeSqrt(qreal x) -{ - return x > 0 ? qSqrt(x) : 0; -} - static void QT_FASTCALL getRadialGradientValues(RadialGradientValues *v, const QSpanData *data) { v->dx = data->gradient.radial.center.x - data->gradient.radial.focal.x; v->dy = data->gradient.radial.center.y - data->gradient.radial.focal.y; - v->a = data->gradient.radial.radius*data->gradient.radial.radius - v->dx*v->dx - v->dy*v->dy; -} - -static const uint * QT_FASTCALL fetchRadialGradient(uint *buffer, const Operator *op, const QSpanData *data, - int y, int x, int length) -{ - const uint *b = buffer; - qreal rx = data->m21 * (y + qreal(0.5)) - + data->dx + data->m11 * (x + qreal(0.5)); - qreal ry = data->m22 * (y + qreal(0.5)) - + data->dy + data->m12 * (x + qreal(0.5)); - bool affine = !data->m13 && !data->m23; - //qreal r = data->gradient.radial.radius; - - const uint *end = buffer + length; - if (affine) { - rx -= data->gradient.radial.focal.x; - ry -= data->gradient.radial.focal.y; - - qreal inv_a = 1 / qreal(2 * op->radial.a); - - const qreal delta_rx = data->m11; - const qreal delta_ry = data->m12; - - qreal b = 2*(rx * op->radial.dx + ry * op->radial.dy); - qreal delta_b = 2*(delta_rx * op->radial.dx + delta_ry * op->radial.dy); - const qreal b_delta_b = 2 * b * delta_b; - const qreal delta_b_delta_b = 2 * delta_b * delta_b; - const qreal bb = b * b; - const qreal delta_bb = delta_b * delta_b; + v->dr = data->gradient.radial.center.radius - data->gradient.radial.focal.radius; + v->sqrfr = data->gradient.radial.focal.radius * data->gradient.radial.focal.radius; - b *= inv_a; - delta_b *= inv_a; + v->a = v->dr * v->dr - v->dx*v->dx - v->dy*v->dy; + v->inv2a = 1 / (2 * v->a); - const qreal rxrxryry = rx * rx + ry * ry; - const qreal delta_rxrxryry = delta_rx * delta_rx + delta_ry * delta_ry; - const qreal rx_plus_ry = 2*(rx * delta_rx + ry * delta_ry); - const qreal delta_rx_plus_ry = 2 * delta_rxrxryry; - - inv_a *= inv_a; - - qreal det = (bb + 4 * op->radial.a * rxrxryry) * inv_a; - qreal delta_det = (b_delta_b + delta_bb + 4 * op->radial.a * (rx_plus_ry + delta_rxrxryry)) * inv_a; - const qreal delta_delta_det = (delta_b_delta_b + 4 * op->radial.a * delta_rx_plus_ry) * inv_a; + v->extended = !qFuzzyIsNull(data->gradient.radial.focal.radius) || v->a <= 0; +} - while (buffer < end) { - *buffer = qt_gradient_pixel(&data->gradient, qSafeSqrt(det) - b); +class RadialFetchPlain +{ +public: + static inline void fetch(uint *buffer, uint *end, const Operator *op, const QSpanData *data, qreal det, + qreal delta_det, qreal delta_delta_det, qreal b, qreal delta_b) + { + if (op->radial.extended) { + while (buffer < end) { + quint32 result = 0; + if (det >= 0) { + qreal w = qSqrt(det) - b; + if (data->gradient.radial.focal.radius + op->radial.dr * w >= 0) + result = qt_gradient_pixel(&data->gradient, w); + } - det += delta_det; - delta_det += delta_delta_det; - b += delta_b; + *buffer = result; - ++buffer; - } - } else { - qreal rw = data->m23 * (y + qreal(0.5)) - + data->m33 + data->m13 * (x + qreal(0.5)); - if (!rw) - rw = 1; - while (buffer < end) { - qreal gx = rx/rw - data->gradient.radial.focal.x; - qreal gy = ry/rw - data->gradient.radial.focal.y; - qreal b = 2*(gx*op->radial.dx + gy*op->radial.dy); - qreal det = determinant(op->radial.a, b , -(gx*gx + gy*gy)); - qreal s = realRoots(op->radial.a, b, qSafeSqrt(det)); + det += delta_det; + delta_det += delta_delta_det; + b += delta_b; - *buffer = qt_gradient_pixel(&data->gradient, s); + ++buffer; + } + } else { + while (buffer < end) { + *buffer++ = qt_gradient_pixel(&data->gradient, qSqrt(det) - b); - rx += data->m11; - ry += data->m12; - rw += data->m13; - if (!rw) { - rw += data->m13; + det += delta_det; + delta_det += delta_delta_det; + b += delta_b; } - ++buffer; } } +}; - return b; +const uint * QT_FASTCALL qt_fetch_radial_gradient_plain(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length) +{ + return qt_fetch_radial_gradient_template<RadialFetchPlain>(buffer, op, data, y, x, length); } -static const uint * QT_FASTCALL fetchConicalGradient(uint *buffer, const Operator *, const QSpanData *data, - int y, int x, int length) +static SourceFetchProc qt_fetch_radial_gradient = qt_fetch_radial_gradient_plain; + +static const uint * QT_FASTCALL qt_fetch_conical_gradient(uint *buffer, const Operator *, const QSpanData *data, + int y, int x, int length) { const uint *b = buffer; qreal rx = data->m21 * (y + qreal(0.5)) @@ -3347,16 +3217,16 @@ static inline Operator getOperator(const QSpanData *data, const QSpan *spans, in case QSpanData::LinearGradient: solidSource = !data->gradient.alphaColor; getLinearGradientValues(&op.linear, data); - op.src_fetch = fetchLinearGradient; + op.src_fetch = qt_fetch_linear_gradient; break; case QSpanData::RadialGradient: solidSource = !data->gradient.alphaColor; getRadialGradientValues(&op.radial, data); - op.src_fetch = fetchRadialGradient; + op.src_fetch = qt_fetch_radial_gradient; break; case QSpanData::ConicalGradient: solidSource = !data->gradient.alphaColor; - op.src_fetch = fetchConicalGradient; + op.src_fetch = qt_fetch_conical_gradient; break; case QSpanData::Texture: op.src_fetch = sourceFetch[getBlendType(data)][data->texture.format]; @@ -7198,14 +7068,8 @@ void qt_build_pow_tables() { #endif #ifdef Q_WS_WIN - int winSmooth; - if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0)) - smoothing = winSmooth / qreal(1000.0); - - // Safeguard ourselves against corrupt registry values... - if (smoothing > 5 || smoothing < 1) - smoothing = qreal(1.4); - + extern qreal qt_fontsmoothing_gamma; // qapplication_win.cpp + smoothing = qt_fontsmoothing_gamma; #endif #ifdef Q_WS_X11 @@ -7888,6 +7752,11 @@ void qInitDrawhelperAsm() qBlendFunctions[QImage::Format_ARGB32_Premultiplied][QImage::Format_RGB32] = qt_blend_rgb32_on_rgb32_sse2; qBlendFunctions[QImage::Format_RGB32][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32_on_argb32_sse2; qBlendFunctions[QImage::Format_ARGB32_Premultiplied][QImage::Format_ARGB32_Premultiplied] = qt_blend_argb32_on_argb32_sse2; + + extern const uint * QT_FASTCALL qt_fetch_radial_gradient_sse2(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length); + + qt_fetch_radial_gradient = qt_fetch_radial_gradient_sse2; } #ifdef QT_HAVE_SSSE3 @@ -7983,6 +7852,11 @@ void qInitDrawhelperAsm() qMemRotateFunctions[QImage::Format_RGB16][0] = qt_memrotate90_16_neon; qMemRotateFunctions[QImage::Format_RGB16][2] = qt_memrotate270_16_neon; qt_memfill32 = qt_memfill32_neon; + + extern const uint * QT_FASTCALL qt_fetch_radial_gradient_neon(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length); + + qt_fetch_radial_gradient = qt_fetch_radial_gradient_neon; } #endif diff --git a/src/gui/painting/qdrawhelper_neon.cpp b/src/gui/painting/qdrawhelper_neon.cpp index debca37..e673dd9 100644 --- a/src/gui/painting/qdrawhelper_neon.cpp +++ b/src/gui/painting/qdrawhelper_neon.cpp @@ -955,6 +955,46 @@ void qt_memrotate270_16_neon(const uchar *srcPixels, int w, int h, } } +class QSimdNeon +{ +public: + typedef int32x4_t Int32x4; + typedef float32x4_t Float32x4; + + union Vect_buffer_i { Int32x4 v; int i[4]; }; + union Vect_buffer_f { Float32x4 v; float f[4]; }; + + static inline Float32x4 v_dup(float x) { return vdupq_n_f32(x); } + static inline Int32x4 v_dup(int x) { return vdupq_n_s32(x); } + static inline Int32x4 v_dup(uint x) { return vdupq_n_s32(x); } + + static inline Float32x4 v_add(Float32x4 a, Float32x4 b) { return vaddq_f32(a, b); } + static inline Int32x4 v_add(Int32x4 a, Int32x4 b) { return vaddq_s32(a, b); } + + static inline Float32x4 v_max(Float32x4 a, Float32x4 b) { return vmaxq_f32(a, b); } + static inline Float32x4 v_min(Float32x4 a, Float32x4 b) { return vminq_f32(a, b); } + static inline Int32x4 v_min_16(Int32x4 a, Int32x4 b) { return vminq_s32(a, b); } + + static inline Int32x4 v_and(Int32x4 a, Int32x4 b) { return vandq_s32(a, b); } + + static inline Float32x4 v_sub(Float32x4 a, Float32x4 b) { return vsubq_f32(a, b); } + static inline Int32x4 v_sub(Int32x4 a, Int32x4 b) { return vsubq_s32(a, b); } + + static inline Float32x4 v_mul(Float32x4 a, Float32x4 b) { return vmulq_f32(a, b); } + + static inline Float32x4 v_sqrt(Float32x4 x) { Float32x4 y = vrsqrteq_f32(x); y = vmulq_f32(y, vrsqrtsq_f32(x, vmulq_f32(y, y))); return vmulq_f32(x, y); } + + static inline Int32x4 v_toInt(Float32x4 x) { return vcvtq_s32_f32(x); } + + static inline Int32x4 v_greaterOrEqual(Float32x4 a, Float32x4 b) { return vcge_f32(a, b); } +}; + +const uint * QT_FASTCALL qt_fetch_radial_gradient_neon(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length) +{ + return qt_fetch_radial_gradient_template<QRadialFetchSimd<QSimdNeon> >(buffer, op, data, y, x, length); +} + QT_END_NAMESPACE #endif // QT_HAVE_NEON diff --git a/src/gui/painting/qdrawhelper_p.h b/src/gui/painting/qdrawhelper_p.h index d4e731b..fa6ad0b 100644 --- a/src/gui/painting/qdrawhelper_p.h +++ b/src/gui/painting/qdrawhelper_p.h @@ -63,6 +63,7 @@ #endif #include "private/qrasterdefs_p.h" #include <private/qsimd_p.h> +#include <private/qmath_p.h> #ifdef Q_WS_QWS #include "QtGui/qscreen_qws.h" @@ -178,6 +179,44 @@ void qBlendTextureCallback(int count, const QSpan *spans, void *userData); typedef void (QT_FASTCALL *CompositionFunction)(uint *dest, const uint *src, int length, uint const_alpha); typedef void (QT_FASTCALL *CompositionFunctionSolid)(uint *dest, int length, uint color, uint const_alpha); +struct LinearGradientValues +{ + qreal dx; + qreal dy; + qreal l; + qreal off; +}; + +struct RadialGradientValues +{ + qreal dx; + qreal dy; + qreal dr; + qreal sqrfr; + qreal a; + qreal inv2a; + bool extended; +}; + +struct Operator; +typedef uint* (QT_FASTCALL *DestFetchProc)(uint *buffer, QRasterBuffer *rasterBuffer, int x, int y, int length); +typedef void (QT_FASTCALL *DestStoreProc)(QRasterBuffer *rasterBuffer, int x, int y, const uint *buffer, int length); +typedef const uint* (QT_FASTCALL *SourceFetchProc)(uint *buffer, const Operator *o, const QSpanData *data, int y, int x, int length); + +struct Operator +{ + QPainter::CompositionMode mode; + DestFetchProc dest_fetch; + DestStoreProc dest_store; + SourceFetchProc src_fetch; + CompositionFunctionSolid funcSolid; + CompositionFunction func; + union { + LinearGradientValues linear; + RadialGradientValues radial; + }; +}; + void qInitDrawhelperAsm(); class QRasterPaintEngine; @@ -204,12 +243,13 @@ struct QRadialGradientData struct { qreal x; qreal y; + qreal radius; } center; struct { qreal x; qreal y; + qreal radius; } focal; - qreal radius; }; struct QConicalGradientData @@ -233,8 +273,10 @@ struct QGradientData #ifdef Q_WS_QWS #define GRADIENT_STOPTABLE_SIZE 256 +#define GRADIENT_STOPTABLE_SIZE_SHIFT 8 #else #define GRADIENT_STOPTABLE_SIZE 1024 +#define GRADIENT_STOPTABLE_SIZE_SHIFT 10 #endif uint* colorTable; //[GRADIENT_STOPTABLE_SIZE]; @@ -308,6 +350,218 @@ struct QSpanData void adjustSpanMethods(); }; +static inline uint qt_gradient_clamp(const QGradientData *data, int ipos) +{ + if (ipos < 0 || ipos >= GRADIENT_STOPTABLE_SIZE) { + if (data->spread == QGradient::RepeatSpread) { + ipos = ipos % GRADIENT_STOPTABLE_SIZE; + ipos = ipos < 0 ? GRADIENT_STOPTABLE_SIZE + ipos : ipos; + } else if (data->spread == QGradient::ReflectSpread) { + const int limit = GRADIENT_STOPTABLE_SIZE * 2; + ipos = ipos % limit; + ipos = ipos < 0 ? limit + ipos : ipos; + ipos = ipos >= GRADIENT_STOPTABLE_SIZE ? limit - 1 - ipos : ipos; + } else { + if (ipos < 0) + ipos = 0; + else if (ipos >= GRADIENT_STOPTABLE_SIZE) + ipos = GRADIENT_STOPTABLE_SIZE-1; + } + } + + Q_ASSERT(ipos >= 0); + Q_ASSERT(ipos < GRADIENT_STOPTABLE_SIZE); + + return ipos; +} + +static inline uint qt_gradient_pixel(const QGradientData *data, qreal pos) +{ + int ipos = int(pos * (GRADIENT_STOPTABLE_SIZE - 1) + qreal(0.5)); + return data->colorTable[qt_gradient_clamp(data, ipos)]; +} + +static inline qreal qRadialDeterminant(qreal a, qreal b, qreal c) +{ + return (b * b) - (4 * a * c); +} + +template <class RadialFetchFunc> +const uint * QT_FASTCALL qt_fetch_radial_gradient_template(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length) +{ + // avoid division by zero + if (qFuzzyIsNull(op->radial.a)) { + extern void (*qt_memfill32)(quint32 *dest, quint32 value, int count); + qt_memfill32(buffer, 0, length); + return buffer; + } + + const uint *b = buffer; + qreal rx = data->m21 * (y + qreal(0.5)) + + data->dx + data->m11 * (x + qreal(0.5)); + qreal ry = data->m22 * (y + qreal(0.5)) + + data->dy + data->m12 * (x + qreal(0.5)); + bool affine = !data->m13 && !data->m23; + + uint *end = buffer + length; + if (affine) { + rx -= data->gradient.radial.focal.x; + ry -= data->gradient.radial.focal.y; + + qreal inv_a = 1 / qreal(2 * op->radial.a); + + const qreal delta_rx = data->m11; + const qreal delta_ry = data->m12; + + qreal b = 2*(op->radial.dr*data->gradient.radial.focal.radius + rx * op->radial.dx + ry * op->radial.dy); + qreal delta_b = 2*(delta_rx * op->radial.dx + delta_ry * op->radial.dy); + const qreal b_delta_b = 2 * b * delta_b; + const qreal delta_b_delta_b = 2 * delta_b * delta_b; + + const qreal bb = b * b; + const qreal delta_bb = delta_b * delta_b; + + b *= inv_a; + delta_b *= inv_a; + + const qreal rxrxryry = rx * rx + ry * ry; + const qreal delta_rxrxryry = delta_rx * delta_rx + delta_ry * delta_ry; + const qreal rx_plus_ry = 2*(rx * delta_rx + ry * delta_ry); + const qreal delta_rx_plus_ry = 2 * delta_rxrxryry; + + inv_a *= inv_a; + + qreal det = (bb - 4 * op->radial.a * (op->radial.sqrfr - rxrxryry)) * inv_a; + qreal delta_det = (b_delta_b + delta_bb + 4 * op->radial.a * (rx_plus_ry + delta_rxrxryry)) * inv_a; + const qreal delta_delta_det = (delta_b_delta_b + 4 * op->radial.a * delta_rx_plus_ry) * inv_a; + + RadialFetchFunc::fetch(buffer, end, op, data, det, delta_det, delta_delta_det, b, delta_b); + } else { + qreal rw = data->m23 * (y + qreal(0.5)) + + data->m33 + data->m13 * (x + qreal(0.5)); + + while (buffer < end) { + if (rw == 0) { + *buffer = 0; + } else { + qreal invRw = 1 / rw; + qreal gx = rx * invRw - data->gradient.radial.focal.x; + qreal gy = ry * invRw - data->gradient.radial.focal.y; + qreal b = 2*(op->radial.dr*data->gradient.radial.focal.radius + gx*op->radial.dx + gy*op->radial.dy); + qreal det = qRadialDeterminant(op->radial.a, b, op->radial.sqrfr - (gx*gx + gy*gy)); + + quint32 result = 0; + if (det >= 0) { + qreal detSqrt = qSqrt(det); + + qreal s0 = (-b - detSqrt) * op->radial.inv2a; + qreal s1 = (-b + detSqrt) * op->radial.inv2a; + + qreal s = qMax(s0, s1); + + if (data->gradient.radial.focal.radius + op->radial.dr * s >= 0) + result = qt_gradient_pixel(&data->gradient, s); + } + + *buffer = result; + } + + rx += data->m11; + ry += data->m12; + rw += data->m13; + + ++buffer; + } + } + + return b; +} + +template <class Simd> +class QRadialFetchSimd +{ +public: + static void fetch(uint *buffer, uint *end, const Operator *op, const QSpanData *data, qreal det, + qreal delta_det, qreal delta_delta_det, qreal b, qreal delta_b) + { + typename Simd::Vect_buffer_f det_vec; + typename Simd::Vect_buffer_f delta_det4_vec; + typename Simd::Vect_buffer_f b_vec; + + for (int i = 0; i < 4; ++i) { + det_vec.f[i] = det; + delta_det4_vec.f[i] = 4 * delta_det; + b_vec.f[i] = b; + + det += delta_det; + delta_det += delta_delta_det; + b += delta_b; + } + + const typename Simd::Float32x4 v_delta_delta_det16 = Simd::v_dup(16 * delta_delta_det); + const typename Simd::Float32x4 v_delta_delta_det6 = Simd::v_dup(6 * delta_delta_det); + const typename Simd::Float32x4 v_delta_b4 = Simd::v_dup(4 * delta_b); + + const typename Simd::Float32x4 v_r0 = Simd::v_dup(data->gradient.radial.focal.radius); + const typename Simd::Float32x4 v_dr = Simd::v_dup(op->radial.dr); + + const typename Simd::Float32x4 v_min = Simd::v_dup(0.0f); + const typename Simd::Float32x4 v_max = Simd::v_dup(float(GRADIENT_STOPTABLE_SIZE-1)); + const typename Simd::Float32x4 v_half = Simd::v_dup(0.5f); + + const typename Simd::Int32x4 v_repeat_mask = Simd::v_dup(~(uint(0xffffff) << GRADIENT_STOPTABLE_SIZE_SHIFT)); + const typename Simd::Int32x4 v_reflect_mask = Simd::v_dup(~(uint(0xffffff) << (GRADIENT_STOPTABLE_SIZE_SHIFT+1))); + + const typename Simd::Int32x4 v_reflect_limit = Simd::v_dup(2 * GRADIENT_STOPTABLE_SIZE - 1); + + const int extended_mask = op->radial.extended ? 0x0 : ~0x0; + +#define FETCH_RADIAL_LOOP_PROLOGUE \ + while (buffer < end) { \ + typename Simd::Vect_buffer_i v_buffer_mask; \ + v_buffer_mask.v = Simd::v_greaterOrEqual(det_vec.v, v_min); \ + const typename Simd::Float32x4 v_index_local = Simd::v_sub(Simd::v_sqrt(Simd::v_max(v_min, det_vec.v)), b_vec.v); \ + const typename Simd::Float32x4 v_index = Simd::v_add(Simd::v_mul(v_index_local, v_max), v_half); \ + v_buffer_mask.v = Simd::v_and(v_buffer_mask.v, Simd::v_greaterOrEqual(Simd::v_add(v_r0, Simd::v_mul(v_dr, v_index_local)), v_min)); \ + typename Simd::Vect_buffer_i index_vec; +#define FETCH_RADIAL_LOOP_CLAMP_REPEAT \ + index_vec.v = Simd::v_and(v_repeat_mask, Simd::v_toInt(v_index)); +#define FETCH_RADIAL_LOOP_CLAMP_REFLECT \ + const typename Simd::Int32x4 v_index_i = Simd::v_and(v_reflect_mask, Simd::v_toInt(v_index)); \ + const typename Simd::Int32x4 v_index_i_inv = Simd::v_sub(v_reflect_limit, v_index_i); \ + index_vec.v = Simd::v_min_16(v_index_i, v_index_i_inv); +#define FETCH_RADIAL_LOOP_CLAMP_PAD \ + index_vec.v = Simd::v_toInt(Simd::v_min(v_max, Simd::v_max(v_min, v_index))); +#define FETCH_RADIAL_LOOP_EPILOGUE \ + det_vec.v = Simd::v_add(Simd::v_add(det_vec.v, delta_det4_vec.v), v_delta_delta_det6); \ + delta_det4_vec.v = Simd::v_add(delta_det4_vec.v, v_delta_delta_det16); \ + b_vec.v = Simd::v_add(b_vec.v, v_delta_b4); \ + for (int i = 0; i < 4; ++i) \ + *buffer++ = (extended_mask | v_buffer_mask.i[i]) & data->gradient.colorTable[index_vec.i[i]]; \ + } + +#define FETCH_RADIAL_LOOP(FETCH_RADIAL_LOOP_CLAMP) \ + FETCH_RADIAL_LOOP_PROLOGUE \ + FETCH_RADIAL_LOOP_CLAMP \ + FETCH_RADIAL_LOOP_EPILOGUE + + switch (data->gradient.spread) { + case QGradient::RepeatSpread: + FETCH_RADIAL_LOOP(FETCH_RADIAL_LOOP_CLAMP_REPEAT) + break; + case QGradient::ReflectSpread: + FETCH_RADIAL_LOOP(FETCH_RADIAL_LOOP_CLAMP_REFLECT) + break; + case QGradient::PadSpread: + FETCH_RADIAL_LOOP(FETCH_RADIAL_LOOP_CLAMP_PAD) + break; + default: + Q_ASSERT(false); + } + } +}; + #if defined(Q_CC_RVCT) # pragma push # pragma arm diff --git a/src/gui/painting/qdrawhelper_sse2.cpp b/src/gui/painting/qdrawhelper_sse2.cpp index aad6bc9..75bb619 100644 --- a/src/gui/painting/qdrawhelper_sse2.cpp +++ b/src/gui/painting/qdrawhelper_sse2.cpp @@ -112,8 +112,6 @@ void qt_blend_rgb32_on_rgb32_sse2(uchar *destPixels, int dbpl, // First, align dest to 16 bytes: ALIGNMENT_PROLOGUE_16BYTES(dst, x, w) { - quint32 s = src[x]; - s = BYTE_MUL(s, const_alpha); dst[x] = INTERPOLATE_PIXEL_255(src[x], const_alpha, dst[x], one_minus_const_alpha); } @@ -127,8 +125,6 @@ void qt_blend_rgb32_on_rgb32_sse2(uchar *destPixels, int dbpl, } } for (; x<w; ++x) { - quint32 s = src[x]; - s = BYTE_MUL(s, const_alpha); dst[x] = INTERPOLATE_PIXEL_255(src[x], const_alpha, dst[x], one_minus_const_alpha); } dst = (quint32 *)(((uchar *) dst) + dbpl); @@ -491,6 +487,58 @@ void qt_bitmapblit16_sse2(QRasterBuffer *rasterBuffer, int x, int y, } } +class QSimdSse2 +{ +public: + typedef __m128i Int32x4; + typedef __m128 Float32x4; + + union Vect_buffer_i { Int32x4 v; int i[4]; }; + union Vect_buffer_f { Float32x4 v; float f[4]; }; + + static inline Float32x4 v_dup(float x) { return _mm_set1_ps(x); } + static inline Float32x4 v_dup(double x) { return _mm_set1_ps(x); } + static inline Int32x4 v_dup(int x) { return _mm_set1_epi32(x); } + static inline Int32x4 v_dup(uint x) { return _mm_set1_epi32(x); } + + static inline Float32x4 v_add(Float32x4 a, Float32x4 b) { return _mm_add_ps(a, b); } + static inline Int32x4 v_add(Int32x4 a, Int32x4 b) { return _mm_add_epi32(a, b); } + + static inline Float32x4 v_max(Float32x4 a, Float32x4 b) { return _mm_max_ps(a, b); } + static inline Float32x4 v_min(Float32x4 a, Float32x4 b) { return _mm_min_ps(a, b); } + static inline Int32x4 v_min_16(Int32x4 a, Int32x4 b) { return _mm_min_epi16(a, b); } + + static inline Int32x4 v_and(Int32x4 a, Int32x4 b) { return _mm_and_si128(a, b); } + + static inline Float32x4 v_sub(Float32x4 a, Float32x4 b) { return _mm_sub_ps(a, b); } + static inline Int32x4 v_sub(Int32x4 a, Int32x4 b) { return _mm_sub_epi32(a, b); } + + static inline Float32x4 v_mul(Float32x4 a, Float32x4 b) { return _mm_mul_ps(a, b); } + + static inline Float32x4 v_sqrt(Float32x4 x) { return _mm_sqrt_ps(x); } + + static inline Int32x4 v_toInt(Float32x4 x) { return _mm_cvttps_epi32(x); } + + // pre-VS 2008 doesn't have cast intrinsics, whereas 2008 and later requires it +#if defined(Q_CC_MSVC) && _MSC_VER < 1500 + static inline Int32x4 v_greaterOrEqual(Float32x4 a, Float32x4 b) + { + union Convert { Int32x4 vi; Float32x4 vf; } convert; + convert.vf = _mm_cmpgt_ps(a, b); + return convert.vi; + } +#else + static inline Int32x4 v_greaterOrEqual(Float32x4 a, Float32x4 b) { return _mm_castps_si128(_mm_cmpgt_ps(a, b)); } +#endif +}; + +const uint * QT_FASTCALL qt_fetch_radial_gradient_sse2(uint *buffer, const Operator *op, const QSpanData *data, + int y, int x, int length) +{ + return qt_fetch_radial_gradient_template<QRadialFetchSimd<QSimdSse2> >(buffer, op, data, y, x, length); +} + + QT_END_NAMESPACE #endif // QT_HAVE_SSE2 diff --git a/src/gui/painting/qgraphicssystem.cpp b/src/gui/painting/qgraphicssystem.cpp index 171ef46..d82fdc9 100644 --- a/src/gui/painting/qgraphicssystem.cpp +++ b/src/gui/painting/qgraphicssystem.cpp @@ -55,6 +55,9 @@ #endif #ifdef Q_OS_SYMBIAN # include <private/qpixmap_s60_p.h> +# include <private/qgraphicssystemex_symbian_p.h> +#else +# include <private/qgraphicssystemex_p.h> #endif QT_BEGIN_NAMESPACE @@ -89,9 +92,18 @@ QPixmapData *QGraphicsSystem::createPixmapData(QPixmapData *origin) return createPixmapData(origin->pixelType()); } -void QGraphicsSystem::releaseCachedResources() +#ifdef Q_OS_SYMBIAN +Q_GLOBAL_STATIC(QSymbianGraphicsSystemEx, symbianPlatformExtension) +#endif + +QGraphicsSystemEx* QGraphicsSystem::platformExtension() { - // Do nothing here +#ifdef Q_OS_SYMBIAN + // this is used on raster graphics systems. HW accelerated + // graphics systems will overwrite this function. + return symbianPlatformExtension(); +#endif + return 0; } QT_END_NAMESPACE diff --git a/src/gui/painting/qgraphicssystem_p.h b/src/gui/painting/qgraphicssystem_p.h index 0f99a31..275f9eb 100644 --- a/src/gui/painting/qgraphicssystem_p.h +++ b/src/gui/painting/qgraphicssystem_p.h @@ -63,6 +63,7 @@ QT_BEGIN_NAMESPACE class QPixmapFilter; class QBlittable; +class QGraphicsSystemEx; class Q_GUI_EXPORT QGraphicsSystem { @@ -77,7 +78,7 @@ public: // to have a graphics system. static QPixmapData *createDefaultPixmapData(QPixmapData::PixelType type); - virtual void releaseCachedResources(); + virtual QGraphicsSystemEx* platformExtension(); }; QT_END_NAMESPACE diff --git a/src/gui/painting/qgraphicssystemex_p.h b/src/gui/painting/qgraphicssystemex_p.h new file mode 100644 index 0000000..6feb116 --- /dev/null +++ b/src/gui/painting/qgraphicssystemex_p.h @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QGRAPHICSSYSTEMEX_P_H +#define QGRAPHICSSYSTEMEX_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include <qglobal.h> + +QT_BEGIN_NAMESPACE + +class Q_GUI_EXPORT QGraphicsSystemEx +{ +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/gui/painting/qgraphicssystemex_symbian.cpp b/src/gui/painting/qgraphicssystemex_symbian.cpp new file mode 100644 index 0000000..2d3f137 --- /dev/null +++ b/src/gui/painting/qgraphicssystemex_symbian.cpp @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qgraphicssystemex_symbian_p.h" +#include "private/qwidget_p.h" +#include "private/qbackingstore_p.h" +#include "private/qapplication_p.h" + +#include <QDebug> + +QT_BEGIN_NAMESPACE + +void QSymbianGraphicsSystemEx::releaseCachedGpuResources() +{ + // Do nothing here + // This is implemented in graphics system specific plugin +} + +void QSymbianGraphicsSystemEx::releaseAllGpuResources() +{ + releaseCachedGpuResources(); + + foreach (QWidget *widget, QApplication::topLevelWidgets()) { + if (QTLWExtra *topExtra = qt_widget_private(widget)->maybeTopData()) + topExtra->backingStore.destroy(); + } +} + +bool QSymbianGraphicsSystemEx::hasBCM2727() +{ + return !QApplicationPrivate::instance()->useTranslucentEGLSurfaces; +} + +void QSymbianGraphicsSystemEx::forceToRaster(QWidget *window) +{ + if (window && window->isWindow()) { + qt_widget_private(window)->createTLExtra(); + if (QTLWExtra *topExtra = qt_widget_private(window)->maybeTopData()) { + topExtra->forcedToRaster = 1; + if (topExtra->backingStore.data()) { + topExtra->backingStore.create(window); + topExtra->backingStore.registerWidget(window); + } + } + } +} + +QT_END_NAMESPACE diff --git a/src/gui/util/qscrollerproperties_p.h b/src/gui/painting/qgraphicssystemex_symbian_p.h index 76d8b0a..0b1e39e 100644 --- a/src/gui/util/qscrollerproperties_p.h +++ b/src/gui/painting/qgraphicssystemex_symbian_p.h @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#ifndef QSCROLLERPROPERTIES_P_H -#define QSCROLLERPROPERTIES_P_H +#ifndef QSYMBIANGRAPHICSSYSTEMEX_P_H +#define QSYMBIANGRAPHICSSYSTEMEX_P_H // // W A R N I N G @@ -53,42 +53,21 @@ // We mean it. // -#include <QPointF> -#include <QEasingCurve> -#include <qscrollerproperties.h> +#include "private/qgraphicssystemex_p.h" QT_BEGIN_NAMESPACE -class QScrollerPropertiesPrivate +class QWidget; + +class Q_GUI_EXPORT QSymbianGraphicsSystemEx : public QGraphicsSystemEx { public: - static QScrollerPropertiesPrivate *defaults(); - - bool operator==(const QScrollerPropertiesPrivate &) const; - - qreal mousePressEventDelay; - qreal dragStartDistance; - qreal dragVelocitySmoothingFactor; - qreal axisLockThreshold; - QEasingCurve scrollingCurve; - qreal decelerationFactor; - qreal minimumVelocity; - qreal maximumVelocity; - qreal maximumClickThroughVelocity; - qreal acceleratingFlickMaximumTime; - qreal acceleratingFlickSpeedupFactor; - qreal snapPositionRatio; - qreal snapTime; - qreal overshootDragResistanceFactor; - qreal overshootDragDistanceFactor; - qreal overshootScrollDistanceFactor; - qreal overshootScrollTime; - QScrollerProperties::OvershootPolicy hOvershootPolicy; - QScrollerProperties::OvershootPolicy vOvershootPolicy; - QScrollerProperties::FrameRates frameRate; + virtual void releaseCachedGpuResources(); + virtual void releaseAllGpuResources(); + virtual bool hasBCM2727(); + virtual void forceToRaster(QWidget *window); }; QT_END_NAMESPACE -#endif // QSCROLLERPROPERTIES_P_H - +#endif diff --git a/src/gui/painting/qgraphicssystemfactory.cpp b/src/gui/painting/qgraphicssystemfactory.cpp index 62a60d7..6212674 100644 --- a/src/gui/painting/qgraphicssystemfactory.cpp +++ b/src/gui/painting/qgraphicssystemfactory.cpp @@ -74,7 +74,7 @@ QGraphicsSystem *QGraphicsSystemFactory::create(const QString& key) if (system.isEmpty()) { system = QLatin1String("runtime"); } -#elif defined (QT_GRAPHICSSYSTEM_RASTER) && !defined(Q_WS_WIN) && !defined(Q_OS_SYMBIAN) || defined(Q_WS_X11) +#elif defined (QT_GRAPHICSSYSTEM_RASTER) && !defined(Q_WS_WIN) && !defined(Q_OS_SYMBIAN) || defined(Q_WS_X11) || (defined (Q_WS_MAC) && defined(QT_MAC_USE_COCOA)) if (system.isEmpty()) { system = QLatin1String("raster"); } diff --git a/src/gui/painting/qpaintbuffer.cpp b/src/gui/painting/qpaintbuffer.cpp index 7870def..6f6cd6f 100644 --- a/src/gui/painting/qpaintbuffer.cpp +++ b/src/gui/painting/qpaintbuffer.cpp @@ -535,16 +535,6 @@ QString QPaintBuffer::commandDescription(int command) const QTextItemInt &ti = (*tiCopy)(); QString text(ti.text()); - QFont font(ti.font()); - font.setUnderline(false); - font.setStrikeOut(false); - font.setOverline(false); - - const QTextItemInt &si = static_cast<const QTextItemInt &>(ti); - qreal justificationWidth = 0; - if (si.justified) - justificationWidth = si.width.toReal(); - debug << "Cmd_DrawTextItem:" << pos << " " << text; break; } case QPaintBufferPrivate::Cmd_SystemStateChanged: { @@ -1778,12 +1768,12 @@ void QPainterReplayer::process(const QPaintBufferCommand &cmd) rawFontD->fontEngine = fontD->engineForScript(QUnicodeTables::Common); rawFontD->fontEngine->ref.ref(); - QGlyphs glyphs; - glyphs.setFont(rawFont); + QGlyphRun glyphs; + glyphs.setRawFont(rawFont); glyphs.setGlyphIndexes(glyphIndexes); glyphs.setPositions(positions); - painter->drawGlyphs(QPointF(), glyphs); + painter->drawGlyphRun(QPointF(), glyphs); break; } #endif diff --git a/src/gui/painting/qpaintengine_mac.cpp b/src/gui/painting/qpaintengine_mac.cpp index 8aab7c7..cc75b86 100644 --- a/src/gui/painting/qpaintengine_mac.cpp +++ b/src/gui/painting/qpaintengine_mac.cpp @@ -1544,8 +1544,9 @@ void QCoreGraphicsPaintEnginePrivate::setFillBrush(const QPointF &offset) QPointF center(radialGrad->center()); QPointF focal(radialGrad->focalPoint()); qreal radius = radialGrad->radius(); + qreal focalRadius = radialGrad->focalRadius(); shading = CGShadingCreateRadial(colorspace, CGPointMake(focal.x(), focal.y()), - 0.0, CGPointMake(center.x(), center.y()), radius, fill_func, false, true); + focalRadius, CGPointMake(center.x(), center.y()), radius, fill_func, false, true); } CGFunctionRelease(fill_func); diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 6902543..2119e30 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -5033,6 +5033,84 @@ void QGradientCache::generateGradientColorTable(const QGradient& gradient, uint bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation); + if (stopCount == 2) { + uint first_color = ARGB_COMBINE_ALPHA(stops[0].second.rgba(), opacity); + uint second_color = ARGB_COMBINE_ALPHA(stops[1].second.rgba(), opacity); + + qreal first_stop = stops[0].first; + qreal second_stop = stops[1].first; + + if (second_stop < first_stop) { + qSwap(first_color, second_color); + qSwap(first_stop, second_stop); + } + + if (colorInterpolation) { + first_color = PREMUL(first_color); + second_color = PREMUL(second_color); + } + + int first_index = qRound(first_stop * (GRADIENT_STOPTABLE_SIZE-1)); + int second_index = qRound(second_stop * (GRADIENT_STOPTABLE_SIZE-1)); + + uint red_first = qRed(first_color) << 16; + uint green_first = qGreen(first_color) << 16; + uint blue_first = qBlue(first_color) << 16; + uint alpha_first = qAlpha(first_color) << 16; + + uint red_second = qRed(second_color) << 16; + uint green_second = qGreen(second_color) << 16; + uint blue_second = qBlue(second_color) << 16; + uint alpha_second = qAlpha(second_color) << 16; + + int i = 0; + for (; i <= qMin(GRADIENT_STOPTABLE_SIZE, first_index); ++i) { + if (colorInterpolation) + colorTable[i] = first_color; + else + colorTable[i] = PREMUL(first_color); + } + + if (i < second_index) { + qreal reciprocal = qreal(1) / (second_index - first_index); + + int red_delta = qRound(int(red_second - red_first) * reciprocal); + int green_delta = qRound(int(green_second - green_first) * reciprocal); + int blue_delta = qRound(int(blue_second - blue_first) * reciprocal); + int alpha_delta = qRound(int(alpha_second - alpha_first) * reciprocal); + + // rounding + red_first += 1 << 15; + green_first += 1 << 15; + blue_first += 1 << 15; + alpha_first += 1 << 15; + + for (; i < qMin(GRADIENT_STOPTABLE_SIZE, second_index); ++i) { + red_first += red_delta; + green_first += green_delta; + blue_first += blue_delta; + alpha_first += alpha_delta; + + const uint color = ((alpha_first << 8) & 0xff000000) | (red_first & 0xff0000) + | ((green_first >> 8) & 0xff00) | (blue_first >> 16); + + if (colorInterpolation) + colorTable[i] = color; + else + colorTable[i] = PREMUL(color); + } + } + + for (; i < GRADIENT_STOPTABLE_SIZE; ++i) { + if (colorInterpolation) + colorTable[i] = second_color; + else + colorTable[i] = PREMUL(second_color); + } + + return; + } + uint current_color = ARGB_COMBINE_ALPHA(stops[0].second.rgba(), opacity); if (stopCount == 1) { current_color = PREMUL(current_color); @@ -5204,10 +5282,11 @@ void QSpanData::setup(const QBrush &brush, int alpha, QPainter::CompositionMode QPointF center = g->center(); radialData.center.x = center.x(); radialData.center.y = center.y(); + radialData.center.radius = g->centerRadius(); QPointF focal = g->focalPoint(); radialData.focal.x = focal.x(); radialData.focal.y = focal.y(); - radialData.radius = g->radius(); + radialData.focal.radius = g->focalRadius(); } break; diff --git a/src/gui/painting/qpaintengine_x11.cpp b/src/gui/painting/qpaintengine_x11.cpp index 94828fb..6ba9a99 100644 --- a/src/gui/painting/qpaintengine_x11.cpp +++ b/src/gui/painting/qpaintengine_x11.cpp @@ -1611,8 +1611,6 @@ void QX11PaintEnginePrivate::fillPolygon_dev(const QPointF *polygonPoints, int p && (fill.style() != Qt::NoBrush) && ((has_fill_texture && fill.texture().hasAlpha()) || antialias || !solid_fill || has_alpha_pen != has_alpha_brush)) { - QRect br = tessellator->tessellate((QPointF *)clippedPoints, clippedCount, - mode == QPaintEngine::WindingMode); if (tessellator->size > 0) { XRenderPictureAttributes attrs; attrs.poly_edge = antialias ? PolyEdgeSmooth : PolyEdgeSharp; @@ -1771,7 +1769,6 @@ void QX11PaintEngine::drawPath(const QPainterPath &path) Q_D(QX11PaintEngine); if (path.isEmpty()) return; - QTransform old_matrix = d->matrix; if (d->has_brush) d->fillPath(path, QX11PaintEnginePrivate::BrushGC, true); diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index 509fb77..7f601eb 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -1012,4 +1012,50 @@ void QPaintEngineEx::updateState(const QPaintEngineState &) // do nothing... } +Q_GUI_EXPORT QPainterPath qt_painterPathFromVectorPath(const QVectorPath &path) +{ + const qreal *points = path.points(); + const QPainterPath::ElementType *types = path.elements(); + + QPainterPath p; + if (types) { + int id = 0; + for (int i=0; i<path.elementCount(); ++i) { + switch(types[i]) { + case QPainterPath::MoveToElement: + p.moveTo(QPointF(points[id], points[id+1])); + id+=2; + break; + case QPainterPath::LineToElement: + p.lineTo(QPointF(points[id], points[id+1])); + id+=2; + break; + case QPainterPath::CurveToElement: { + QPointF p1(points[id], points[id+1]); + QPointF p2(points[id+2], points[id+3]); + QPointF p3(points[id+4], points[id+5]); + p.cubicTo(p1, p2, p3); + id+=6; + break; + } + case QPainterPath::CurveToDataElement: + ; + break; + } + } + } else { + p.moveTo(QPointF(points[0], points[1])); + int id = 2; + for (int i=1; i<path.elementCount(); ++i) { + p.lineTo(QPointF(points[id], points[id+1])); + id+=2; + } + } + if (path.hints() & QVectorPath::WindingFill) + p.setFillRule(Qt::WindingFill); + + return p; +} + + QT_END_NAMESPACE diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 9fafba5..a965c15 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -62,7 +62,7 @@ #include "qthread.h" #include "qvarlengtharray.h" #include "qstatictext.h" -#include "qglyphs.h" +#include "qglyphrun.h" #include <private/qfontengine_p.h> #include <private/qpaintengine_p.h> @@ -73,7 +73,7 @@ #include <private/qpaintengine_raster_p.h> #include <private/qmath_p.h> #include <private/qstatictext_p.h> -#include <private/qglyphs_p.h> +#include <private/qglyphrun_p.h> #include <private/qstylehelper_p.h> #include <private/qrawfont_p.h> @@ -156,7 +156,8 @@ static bool qt_paintengine_supports_transformations(QPaintEngine::Type type) { return type == QPaintEngine::OpenGL2 || type == QPaintEngine::OpenVG - || type == QPaintEngine::OpenGL; + || type == QPaintEngine::OpenGL + || type == QPaintEngine::CoreGraphics; } #ifndef QT_NO_DEBUG @@ -503,8 +504,12 @@ void QPainterPrivate::draw_helper(const QPainterPath &originalPath, DrawOperatio q->save(); state->matrix = QTransform(); - state->dirtyFlags |= QPaintEngine::DirtyTransform; - updateState(state); + if (extended) { + extended->transformChanged(); + } else { + state->dirtyFlags |= QPaintEngine::DirtyTransform; + updateState(state); + } engine->drawImage(absPathRect, image, QRectF(0, 0, absPathRect.width(), absPathRect.height()), @@ -687,11 +692,14 @@ void QPainterPrivate::updateInvMatrix() invMatrix = state->matrix.inverted(); } +Q_GUI_EXPORT bool qt_isExtendedRadialGradient(const QBrush &brush); + void QPainterPrivate::updateEmulationSpecifier(QPainterState *s) { bool alpha = false; bool linearGradient = false; bool radialGradient = false; + bool extendedRadialGradient = false; bool conicalGradient = false; bool patternBrush = false; bool xform = false; @@ -723,6 +731,7 @@ void QPainterPrivate::updateEmulationSpecifier(QPainterState *s) (brushStyle == Qt::LinearGradientPattern)); radialGradient = ((penBrushStyle == Qt::RadialGradientPattern) || (brushStyle == Qt::RadialGradientPattern)); + extendedRadialGradient = radialGradient && (qt_isExtendedRadialGradient(penBrush) || qt_isExtendedRadialGradient(s->brush)); conicalGradient = ((penBrushStyle == Qt::ConicalGradientPattern) || (brushStyle == Qt::ConicalGradientPattern)); patternBrush = (((penBrushStyle > Qt::SolidPattern @@ -806,7 +815,7 @@ void QPainterPrivate::updateEmulationSpecifier(QPainterState *s) s->emulationSpecifier &= ~QPaintEngine::LinearGradientFill; // Radial gradient emulation - if (radialGradient && !engine->hasFeature(QPaintEngine::RadialGradientFill)) + if (extendedRadialGradient || (radialGradient && !engine->hasFeature(QPaintEngine::RadialGradientFill))) s->emulationSpecifier |= QPaintEngine::RadialGradientFill; else s->emulationSpecifier &= ~QPaintEngine::RadialGradientFill; @@ -5789,19 +5798,19 @@ void QPainter::drawImage(const QRectF &targetRect, const QImage &image, const QR \since 4.8 - \sa QGlyphs::setFont(), QGlyphs::setPositions(), QGlyphs::setGlyphIndexes() + \sa QGlyphRun::setRawFont(), QGlyphRun::setPositions(), QGlyphRun::setGlyphIndexes() */ #if !defined(QT_NO_RAWFONT) -void QPainter::drawGlyphs(const QPointF &position, const QGlyphs &glyphs) +void QPainter::drawGlyphRun(const QPointF &position, const QGlyphRun &glyphRun) { Q_D(QPainter); - QRawFont font = glyphs.font(); + QRawFont font = glyphRun.rawFont(); if (!font.isValid()) return; - QVector<quint32> glyphIndexes = glyphs.glyphIndexes(); - QVector<QPointF> glyphPositions = glyphs.positions(); + QVector<quint32> glyphIndexes = glyphRun.glyphIndexes(); + QVector<QPointF> glyphPositions = glyphRun.positions(); int count = qMin(glyphIndexes.size(), glyphPositions.size()); QVarLengthArray<QFixedPoint, 128> fixedPointPositions(count); @@ -5809,7 +5818,14 @@ void QPainter::drawGlyphs(const QPointF &position, const QGlyphs &glyphs) bool paintEngineSupportsTransformations = d->extended != 0 ? qt_paintengine_supports_transformations(d->extended->type()) - : false; + : qt_paintengine_supports_transformations(d->engine->type()); + + // If the matrix is not affine, the paint engine will fall back to + // drawing the glyphs as paths, which in turn means we should not + // preprocess the glyph positions + if (!d->state->matrix.isAffine()) + paintEngineSupportsTransformations = true; + for (int i=0; i<count; ++i) { QPointF processedPosition = position + glyphPositions.at(i); if (!paintEngineSupportsTransformations) @@ -5817,8 +5833,8 @@ void QPainter::drawGlyphs(const QPointF &position, const QGlyphs &glyphs) fixedPointPositions[i] = QFixedPoint::fromPointF(processedPosition); } - d->drawGlyphs(glyphIndexes.data(), fixedPointPositions.data(), count, font, glyphs.overline(), - glyphs.underline(), glyphs.strikeOut()); + d->drawGlyphs(glyphIndexes.data(), fixedPointPositions.data(), count, font, glyphRun.overline(), + glyphRun.underline(), glyphRun.strikeOut()); } void QPainterPrivate::drawGlyphs(quint32 *glyphArray, QFixedPoint *positions, int glyphCount, @@ -5853,7 +5869,7 @@ void QPainterPrivate::drawGlyphs(quint32 *glyphArray, QFixedPoint *positions, in QFixed width = rightMost - leftMost; - if (extended != 0) { + if (extended != 0 && state->matrix.isAffine()) { QStaticTextItem staticTextItem; staticTextItem.color = state->pen.color(); staticTextItem.font = state->font; diff --git a/src/gui/painting/qpainter.h b/src/gui/painting/qpainter.h index 4b2c447..601c386 100644 --- a/src/gui/painting/qpainter.h +++ b/src/gui/painting/qpainter.h @@ -79,7 +79,7 @@ class QTextItem; class QMatrix; class QTransform; class QStaticText; -class QGlyphs; +class QGlyphRun; class QPainterPrivateDeleter; @@ -400,7 +400,7 @@ public: Qt::LayoutDirection layoutDirection() const; #if !defined(QT_NO_RAWFONT) - void drawGlyphs(const QPointF &position, const QGlyphs &glyphs); + void drawGlyphRun(const QPointF &position, const QGlyphRun &glyphRun); #endif void drawStaticText(const QPointF &topLeftPosition, const QStaticText &staticText); @@ -553,6 +553,7 @@ private: friend class QPaintEngine; friend class QPaintEngineExPrivate; friend class QOpenGLPaintEngine; + friend class QVGPaintEngine; friend class QX11PaintEngine; friend class QX11PaintEnginePrivate; friend class QWin32PaintEngine; diff --git a/src/gui/painting/qpainterpath.cpp b/src/gui/painting/qpainterpath.cpp index 27aed32..9fbac13 100644 --- a/src/gui/painting/qpainterpath.cpp +++ b/src/gui/painting/qpainterpath.cpp @@ -1126,6 +1126,7 @@ void QPainterPath::addText(const QPointF &point, const QFont &f, const QString & QTextEngine *eng = layout.engine(); layout.beginLayout(); QTextLine line = layout.createLine(); + Q_UNUSED(line); layout.endLayout(); const QScriptLine &sl = eng->lines[0]; if (!sl.length || !eng->layoutData) diff --git a/src/gui/painting/qprintengine_pdf.cpp b/src/gui/painting/qprintengine_pdf.cpp index b7f5160..353869f 100644 --- a/src/gui/painting/qprintengine_pdf.cpp +++ b/src/gui/painting/qprintengine_pdf.cpp @@ -534,7 +534,10 @@ int QPdfEnginePrivate::addImage(const QImage &img, bool *bitmap, qint64 serial_n QImage image = img; QImage::Format format = image.format(); - if (image.depth() == 1 && *bitmap && img.colorTable().size() == 0) { + if (image.depth() == 1 && *bitmap && img.colorTable().size() == 2 + && img.colorTable().at(0) == QColor(Qt::black).rgba() + && img.colorTable().at(1) == QColor(Qt::white).rgba()) + { if (format == QImage::Format_MonoLSB) image = image.convertToFormat(QImage::Format_Mono); format = QImage::Format_Mono; diff --git a/src/gui/painting/qstroker.cpp b/src/gui/painting/qstroker.cpp index fca46b4..dd723ed 100644 --- a/src/gui/painting/qstroker.cpp +++ b/src/gui/painting/qstroker.cpp @@ -552,6 +552,7 @@ void QStroker::joinPoints(qfixed focal_x, qfixed focal_y, const QLineF &nextLine // // line to the beginning of the arc segment, (should not be needed). // emitLineTo(qt_real_to_fixed(curve_start.x()), qt_real_to_fixed(curve_start.y())); + Q_UNUSED(curve_start); for (int i=0; i<point_count; i+=3) { emitCubicTo(qt_real_to_fixed(curves[i].x()), diff --git a/src/gui/painting/qtextureglyphcache.cpp b/src/gui/painting/qtextureglyphcache.cpp index 53f025f..e9e56a2 100644 --- a/src/gui/painting/qtextureglyphcache.cpp +++ b/src/gui/painting/qtextureglyphcache.cpp @@ -296,7 +296,7 @@ void QTextureGlyphCache::fillInPendingGlyphs() QImage QTextureGlyphCache::textureMapForGlyph(glyph_t g, QFixed subPixelPosition) const { #if defined(Q_WS_X11) - if (m_transform.type() > QTransform::TxTranslate) { + if (m_transform.type() > QTransform::TxTranslate && m_current_fontengine->type() == QFontEngine::Freetype) { QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_None; QImage::Format imageFormat = QImage::Format_Invalid; switch (m_type) { diff --git a/src/gui/painting/qunifiedtoolbarsurface_mac.cpp b/src/gui/painting/qunifiedtoolbarsurface_mac.cpp index 3876c3d..2fda6b9 100644 --- a/src/gui/painting/qunifiedtoolbarsurface_mac.cpp +++ b/src/gui/painting/qunifiedtoolbarsurface_mac.cpp @@ -152,7 +152,8 @@ void QUnifiedToolbarSurface::beginPaint(const QRegion &rgn) void QUnifiedToolbarSurface::updateToolbarOffset(QWidget *widget) { QMainWindowLayout *mlayout = qobject_cast<QMainWindowLayout*> (widget->window()->layout()); - mlayout->updateUnifiedToolbarOffset(); + if (mlayout) + mlayout->updateUnifiedToolbarOffset(); } void QUnifiedToolbarSurface::flush(QWidget *widget, const QRegion ®ion, const QPoint &offset) diff --git a/src/gui/painting/qunifiedtoolbarsurface_mac_p.h b/src/gui/painting/qunifiedtoolbarsurface_mac_p.h index 0a7ebf1..ce07f5c 100644 --- a/src/gui/painting/qunifiedtoolbarsurface_mac_p.h +++ b/src/gui/painting/qunifiedtoolbarsurface_mac_p.h @@ -65,6 +65,39 @@ QT_BEGIN_NAMESPACE class QNativeImage; +// +// This is the implementation of the unified toolbar on Mac OS X +// with the graphics system raster. +// +// General idea: +// ------------- +// We redirect the painting of widgets inside the unified toolbar +// to a special window surface, the QUnifiedToolbarSurface. +// We need a separate window surface because the unified toolbar +// is out of the content view. +// The input system is the same as for the unified toolbar with the +// native (CoreGraphics) engine. +// +// Execution flow: +// --------------- +// The unified toolbar is triggered by QMainWindow::setUnifiedTitleAndToolBarOnMac(). +// It calls QMainWindowLayout::insertIntoMacToolbar() which will +// set all the appropriate variables (offsets, redirection, ...). +// When Qt tells a widget to repaint, QWidgetPrivate::drawWidget() +// checks if the widget is inside the unified toolbar and exits without +// painting is that is the case. +// We trigger the rendering of the unified toolbar in QWidget::repaint() +// and QWidget::update(). +// We keep track of flush requests via "flushRequested" variable. That +// allow flush() to be a no-op if no repaint occurred for a widget. +// We rely on the needsDisplay: and drawRect: mecanism for drawing our +// content into the graphics context. +// +// Notes: +// ------ +// The painting of items inside the unified toolbar is expensive. +// Too many repaints will drastically slow down the whole application. +// class QUnifiedToolbarSurfacePrivate { diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp index cc5fe10..786aab3 100644 --- a/src/gui/styles/qcleanlooksstyle.cpp +++ b/src/gui/styles/qcleanlooksstyle.cpp @@ -841,7 +841,6 @@ void QCleanlooksStyle::drawPrimitive(PrimitiveElement elem, case PE_PanelButtonTool: painter->save(); if ((option->state & State_Enabled || option->state & State_On) || !(option->state & State_AutoRaise)) { - QRect rect = option->rect; QPen oldPen = painter->pen(); if (widget && widget->inherits("QDockWidgetTitleButton")) { @@ -1241,7 +1240,6 @@ void QCleanlooksStyle::drawPrimitive(PrimitiveElement elem, if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option)) { QColor borderColor = darkOutline.lighter(110); QColor alphaCornerColor = mergedColors(borderColor, option->palette.background().color()); - QColor innerShadow = mergedColors(borderColor, option->palette.base().color()); int borderThickness = proxy()->pixelMetric(PM_TabBarBaseOverlap, twf, widget); bool reverse = (twf->direction == Qt::RightToLeft); @@ -1879,7 +1877,6 @@ void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *o } else { alphaCornerColor = mergedColors(option->palette.background().color(), borderColor); } - QColor alphaTextColor = mergedColors(option->palette.background().color(), option->palette.text().color()); if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) { painter->fillRect(menuItem->rect, menuBackground); int w = 0; @@ -2220,7 +2217,6 @@ void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *o && tabBarAlignment == Qt::AlignLeft); QColor light = tab->palette.light().color(); - QColor midlight = tab->palette.midlight().color(); QColor background = tab->palette.background().color(); int borderThinkness = proxy()->pixelMetric(PM_TabBarBaseOverlap, tab, widget); @@ -2444,14 +2440,6 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp QColor gradientStartColor = option->palette.button().color().lighter(108); QColor gradientStopColor = mergedColors(option->palette.button().color().darker(108), dark.lighter(150), 70); - QColor highlightedGradientStartColor = option->palette.button().color(); - QColor highlightedGradientStopColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 85); - - QColor highlightedDarkInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 35); - QColor highlightedLightInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 58); - - QColor buttonShadowAlpha = option->palette.background().color().darker(105); - QPalette palette = option->palette; switch (control) { @@ -3437,7 +3425,6 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) { QRect groove = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget); QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget); - QRect ticks = proxy()->subControlRect(CC_Slider, option, SC_SliderTickmarks, widget); bool horizontal = slider->orientation == Qt::Horizontal; bool ticksAbove = slider->tickPosition & QSlider::TicksAbove; @@ -3539,8 +3526,6 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp QRect pixmapRect(0, 0, handle.width(), handle.height()); QPainter handlePainter(&cache); - QColor highlightedGradientStartColor = option->palette.button().color(); - QColor highlightedGradientStopColor = option->palette.light().color(); QColor gradientStartColor = mergedColors(option->palette.button().color().lighter(155), dark.lighter(155), 50); QColor gradientStopColor = gradientStartColor.darker(108); @@ -3557,7 +3542,6 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp } // gradient fill - QRect innerBorder = gradRect; QRect r = pixmapRect.adjusted(1, 1, -1, -1); qt_cleanlooks_draw_gradient(&handlePainter, gradRect, diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp index 3d04c9a..95ebdb4 100644 --- a/src/gui/styles/qcommonstyle.cpp +++ b/src/gui/styles/qcommonstyle.cpp @@ -916,6 +916,7 @@ static QSizeF viewItemTextLayout(QTextLayout &textLayout, int lineWidth) return QSizeF(widthUsed, height); } + void QCommonStylePrivate::viewItemDrawText(QPainter *p, const QStyleOptionViewItemV4 *option, const QRect &rect) const { Q_Q(const QCommonStyle); @@ -933,7 +934,7 @@ void QCommonStylePrivate::viewItemDrawText(QPainter *p, const QStyleOptionViewIt textLayout.setFont(option->font); textLayout.setText(option->text); - QSizeF textLayoutSize = viewItemTextLayout(textLayout, textRect.width()); + viewItemTextLayout(textLayout, textRect.width()); QString elidedText; qreal height = 0; diff --git a/src/gui/styles/qgtkpainter.cpp b/src/gui/styles/qgtkpainter.cpp index 68ade04..6258fe4 100644 --- a/src/gui/styles/qgtkpainter.cpp +++ b/src/gui/styles/qgtkpainter.cpp @@ -586,7 +586,6 @@ void QGtkPainter::paintShadow(GtkWidget *gtkWidget, const gchar* part, if (!rect.isValid()) return; - QRect r = rect; QPixmap cache; QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size()) % pmKey; if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) { @@ -605,7 +604,6 @@ void QGtkPainter::paintFlatBox(GtkWidget *gtkWidget, const gchar* part, { if (!rect.isValid()) return; - QRect r = rect; QPixmap cache; QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size()) % pmKey; if (!m_usePixmapCache || !QPixmapCache::find(pixmapName, cache)) { @@ -632,7 +630,6 @@ void QGtkPainter::paintExtention(GtkWidget *gtkWidget, if (!rect.isValid()) return; - QRect r = rect; QPixmap cache; QString pixmapName = uniqueName(QLS(part), state, shadow, rect.size(), gtkWidget) % HexString<uchar>(gap_pos); @@ -660,7 +657,6 @@ void QGtkPainter::paintOption(GtkWidget *gtkWidget, const QRect &radiorect, if (!rect.isValid()) return; - QRect r = rect; QPixmap cache; QString pixmapName = uniqueName(detail, state, shadow, rect.size()); GdkRectangle gtkCliprect = {0, 0, rect.width(), rect.height()}; @@ -692,7 +688,6 @@ void QGtkPainter::paintCheckbox(GtkWidget *gtkWidget, const QRect &checkrect, if (!rect.isValid()) return; - QRect r = rect; QPixmap cache; QString pixmapName = uniqueName(detail, state, shadow, rect.size()); GdkRectangle gtkCliprect = {0, 0, rect.width(), rect.height()}; diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 277e302..d6dd527 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -782,7 +782,6 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, GtkStateType state = gtkPainter.gtkState(option); style = gtkTreeHeader->style; GtkArrowType type = GTK_ARROW_UP; - QRect r = header->rect; QImage arrow; // This sorting indicator inversion is intentional, and follows the GNOME HIG. // See http://library.gnome.org/devel/hig-book/stable/controls-lists.html.en#controls-lists-sortable @@ -1857,7 +1856,6 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom editArea.setRight(upRect.left()); } if (spinBox->frame) { - GtkShadowType shadow = GTK_SHADOW_OUT; GtkStateType state = gtkPainter.gtkState(option); if (!(option->state & State_Enabled)) @@ -1867,7 +1865,6 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom else if (state == GTK_STATE_PRELIGHT) state = GTK_STATE_NORMAL; - shadow = GTK_SHADOW_IN; style = gtkPainter.getStyle(gtkSpinButton); diff --git a/src/gui/styles/qplastiquestyle.cpp b/src/gui/styles/qplastiquestyle.cpp index 02ce60e..1d33212 100644 --- a/src/gui/styles/qplastiquestyle.cpp +++ b/src/gui/styles/qplastiquestyle.cpp @@ -2007,14 +2007,10 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op } else { alphaCornerColor = mergedColors(option->palette.background().color(), borderColor); } - QColor alphaTextColor = mergedColors(option->palette.background().color(), option->palette.text().color()); QColor gradientStartColor = option->palette.button().color().lighter(104); QColor gradientStopColor = option->palette.button().color().darker(105); - QColor shadowGradientStartColor = option->palette.button().color().darker(115); - QColor shadowGradientStopColor = option->palette.button().color().darker(120); - QColor highlightedGradientStartColor = option->palette.button().color().lighter(101); QColor highlightedGradientStopColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 85); @@ -2025,8 +2021,6 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op QColor highlightedLightInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 58); QColor alphaInnerColor = mergedColors(highlightedDarkInnerBorderColor, option->palette.base().color()); - QColor lightShadow = lightShadowGradientStartColor; - QColor shadow = shadowGradientStartColor; switch (element) { #ifndef QT_NO_TABBAR @@ -3786,10 +3780,6 @@ void QPlastiqueStyle::drawComplexControl(ComplexControl control, const QStyleOpt } QColor gradientStartColor = option->palette.button().color().lighter(104); QColor gradientStopColor = option->palette.button().color().darker(105); - QColor highlightedGradientStartColor = option->palette.button().color().lighter(101); - QColor highlightedGradientStopColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 85); - QColor highlightedDarkInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 35); - QColor highlightedLightInnerBorderColor = mergedColors(option->palette.button().color(), option->palette.highlight().color(), 58); switch (control) { #ifndef QT_NO_SLIDER @@ -3797,7 +3787,6 @@ void QPlastiqueStyle::drawComplexControl(ComplexControl control, const QStyleOpt if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) { QRect grooveRegion = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget); QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget); - QRect ticks = proxy()->subControlRect(CC_Slider, option, SC_SliderTickmarks, widget); bool horizontal = slider->orientation == Qt::Horizontal; bool ticksAbove = slider->tickPosition & QSlider::TicksAbove; bool ticksBelow = slider->tickPosition & QSlider::TicksBelow; diff --git a/src/gui/styles/qwindowsstyle.cpp b/src/gui/styles/qwindowsstyle.cpp index 1dcfd00..754486e 100644 --- a/src/gui/styles/qwindowsstyle.cpp +++ b/src/gui/styles/qwindowsstyle.cpp @@ -2028,10 +2028,8 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai && tabBarAlignment == Qt::AlignLeft); QColor light = tab->palette.light().color(); - QColor midlight = tab->palette.midlight().color(); QColor dark = tab->palette.dark().color(); QColor shadow = tab->palette.shadow().color(); - QColor background = tab->palette.background().color(); int borderThinkness = proxy()->pixelMetric(PM_TabBarBaseOverlap, tab, widget); if (selected) borderThinkness /= 2; diff --git a/src/gui/text/qfont.h b/src/gui/text/qfont.h index 8dbc746..0c7b6f8 100644 --- a/src/gui/text/qfont.h +++ b/src/gui/text/qfont.h @@ -239,7 +239,7 @@ public: bool isCopyOf(const QFont &) const; #ifdef Q_COMPILER_RVALUE_REFS inline QFont &operator=(QFont &&other) - { qSwap(d, other.d); return *this; } + { qSwap(d, other.d); qSwap(resolve_mask, other.resolve_mask); return *this; } #endif #ifdef Q_WS_WIN diff --git a/src/gui/text/qfont_mac.cpp b/src/gui/text/qfont_mac.cpp index daf68c0..044fd84 100644 --- a/src/gui/text/qfont_mac.cpp +++ b/src/gui/text/qfont_mac.cpp @@ -43,6 +43,7 @@ #include "qfont_p.h" #include "qfontengine_p.h" #include "qfontengine_mac_p.h" +#include "qfontengine_coretext_p.h" #include "qfontinfo.h" #include "qfontmetrics.h" #include "qpaintdevice.h" @@ -119,10 +120,10 @@ quint32 QFont::macFontID() const // ### need 64-bit version // Returns an ATSUFonFamilyRef Qt::HANDLE QFont::handle() const { -#if 0 +#ifdef QT_MAC_USE_COCOA QFontEngine *fe = d->engineForScript(QUnicodeTables::Common); - if (fe && fe->type() == QFontEngine::Mac) - return (Qt::HANDLE)static_cast<QFontEngineMacMulti*>(fe)->fontFamilyRef(); + if (fe && fe->type() == QFontEngine::Multi) + return (Qt::HANDLE)static_cast<QCoreTextFontEngineMulti*>(fe)->macFontID(); #endif return 0; } diff --git a/src/gui/text/qfontdatabase_s60.cpp b/src/gui/text/qfontdatabase_s60.cpp index 1db4a7d..3ab1ac8 100644 --- a/src/gui/text/qfontdatabase_s60.cpp +++ b/src/gui/text/qfontdatabase_s60.cpp @@ -152,7 +152,6 @@ public: COpenFontRasterizer *m_rasterizer; mutable QList<const QSymbianTypeFaceExtras *> m_extras; - mutable QHash<QString, const QSymbianTypeFaceExtras *> m_extrasHash; mutable QSet<QString> m_applicationFontFamilies; }; @@ -255,8 +254,9 @@ void QSymbianFontDatabaseExtrasImplementation::clear() static_cast<const QSymbianFontDatabaseExtrasImplementation*>(db->symbianExtras); if (!dbExtras) return; // initializeDb() has never been called + QSymbianTypeFaceExtrasHash &extrasHash = S60->fontData(); if (QSymbianTypeFaceExtras::symbianFontTableApiAvailable()) { - qDeleteAll(dbExtras->m_extrasHash); + qDeleteAll(extrasHash); } else { typedef QList<const QSymbianTypeFaceExtras *>::iterator iterator; for (iterator p = dbExtras->m_extras.begin(); p != dbExtras->m_extras.end(); ++p) { @@ -265,11 +265,16 @@ void QSymbianFontDatabaseExtrasImplementation::clear() } dbExtras->m_extras.clear(); } - dbExtras->m_extrasHash.clear(); + extrasHash.clear(); } void qt_cleanup_symbianFontDatabase() { + static bool cleanupDone = false; + if (cleanupDone) + return; + cleanupDone = true; + QFontDatabasePrivate *db = privateDb(); if (!db) return; @@ -320,9 +325,12 @@ COpenFont* OpenFontFromBitmapFont(const CBitmapFont* aBitmapFont) const QSymbianTypeFaceExtras *QSymbianFontDatabaseExtrasImplementation::extras(const QString &aTypeface, bool bold, bool italic) const { + QSymbianTypeFaceExtrasHash &extrasHash = S60->fontData(); + if (extrasHash.isEmpty() && QThread::currentThread() != QApplication::instance()->thread()) + S60->addThreadLocalReleaseFunc(clear); const QString typeface = qt_symbian_fontNameWithAppFontMarker(aTypeface); const QString searchKey = typeface + QString::number(int(bold)) + QString::number(int(italic)); - if (!m_extrasHash.contains(searchKey)) { + if (!extrasHash.contains(searchKey)) { TFontSpec searchSpec(qt_QString2TPtrC(typeface), 1); if (bold) searchSpec.iFontStyle.SetStrokeWeight(EStrokeWeightBold); @@ -336,7 +344,7 @@ const QSymbianTypeFaceExtras *QSymbianFontDatabaseExtrasImplementation::extras(c QScopedPointer<CFont, CFontFromScreenDeviceReleaser> sFont(font); QSymbianTypeFaceExtras *extras = new QSymbianTypeFaceExtras(font); sFont.take(); - m_extrasHash.insert(searchKey, extras); + extrasHash.insert(searchKey, extras); } else { const TInt err = m_store->GetNearestFontToDesignHeightInPixels(font, searchSpec); Q_ASSERT(err == KErrNone && font); @@ -350,20 +358,20 @@ const QSymbianTypeFaceExtras *QSymbianFontDatabaseExtrasImplementation::extras(c const TOpenFontFaceAttrib* const attrib = openFont->FaceAttrib(); const QString foundKey = QString((const QChar*)attrib->FullName().Ptr(), attrib->FullName().Length()); - if (!m_extrasHash.contains(foundKey)) { + if (!extrasHash.contains(foundKey)) { QScopedPointer<CFont, CFontFromFontStoreReleaser> sFont(font); QSymbianTypeFaceExtras *extras = new QSymbianTypeFaceExtras(font, openFont); sFont.take(); m_extras.append(extras); - m_extrasHash.insert(searchKey, extras); - m_extrasHash.insert(foundKey, extras); + extrasHash.insert(searchKey, extras); + extrasHash.insert(foundKey, extras); } else { m_store->ReleaseFont(font); - m_extrasHash.insert(searchKey, m_extrasHash.value(foundKey)); + extrasHash.insert(searchKey, extrasHash.value(foundKey)); } } } - return m_extrasHash.value(searchKey); + return extrasHash.value(searchKey); } void QSymbianFontDatabaseExtrasImplementation::removeAppFontData( @@ -956,7 +964,7 @@ bool QFontDatabase::removeAllApplicationFonts() bool QFontDatabase::supportsThreadedFontRendering() { - return false; + return QSymbianTypeFaceExtras::symbianFontTableApiAvailable(); } static diff --git a/src/gui/text/qfontengine_coretext.mm b/src/gui/text/qfontengine_coretext.mm index 20b3730..cbf51e6 100644 --- a/src/gui/text/qfontengine_coretext.mm +++ b/src/gui/text/qfontengine_coretext.mm @@ -162,8 +162,10 @@ uint QCoreTextFontEngineMulti::fontIndexForFont(CTFontRef font) const return engines.count() - 1; } -bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, - unsigned short *logClusters, const HB_CharAttributes *) const +bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, + int *nglyphs, QTextEngine::ShaperFlags flags, + unsigned short *logClusters, const HB_CharAttributes *, + QScriptItem *si) const { QCFType<CFStringRef> cfstring = CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar *>(str), @@ -180,6 +182,8 @@ bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLay &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); typeSetter = CTTypesetterCreateWithAttributedStringAndOptions(attributedString, options); } else +#else + Q_UNUSED(flags); #endif typeSetter = CTTypesetterCreateWithAttributedString(attributedString); @@ -219,6 +223,25 @@ bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLay Q_ASSERT((CTRunGetStatus(run) & kCTRunStatusRightToLeft) == rtl); CFRange stringRange = CTRunGetStringRange(run); + int prepend = 0; +#if MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5 + UniChar beginGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location); + QChar dir = QChar::direction(beginGlyph); + bool beginWithOverride = dir == QChar::DirLRO || dir == QChar::DirRLO || dir == QChar::DirLRE || dir == QChar::DirRLE; + if (beginWithOverride) { + logClusters[stringRange.location] = 0; + outGlyphs[0] = 0xFFFF; + outAdvances_x[0] = 0; + outAdvances_y[0] = 0; + outAttributes[0].clusterStart = true; + outAttributes[0].dontPrint = true; + outGlyphs++; + outAdvances_x++; + outAdvances_y++; + outAttributes++; + prepend = 1; + } +#endif UniChar endGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location + stringRange.length - 1); bool endWithPDF = QChar::direction(endGlyph) == QChar::DirPDF; if (endWithPDF) @@ -233,7 +256,12 @@ bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLay if (!runAttribs) runAttribs = attributeDict; CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttribs, NSFontAttributeName)); - const uint fontIndex = (fontIndexForFont(runFont) << 24); + uint fontIndex = fontIndexForFont(runFont); + const QFontEngine *engine = engineAt(fontIndex); + fontIndex <<= 24; + si->ascent = qMax(engine->ascent(), si->ascent); + si->descent = qMax(engine->descent(), si->descent); + si->leading = qMax(engine->leading(), si->leading); //NSLog(@"Run Font Name = %@", CTFontCopyFamilyName(runFont)); if (endWithPDF) glyphCount--; @@ -271,9 +299,9 @@ bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLay CFIndex k = 0; CFIndex i = 0; - for (i = stringRange.location; + for (i = stringRange.location + prepend; (i < stringRange.location + stringRange.length) && (k < glyphCount); ++i) { - if (tmpIndices[k * rtlSign + rtlOffset] == i || i == stringRange.location) { + if (tmpIndices[k * rtlSign + rtlOffset] == i || i == stringRange.location + prepend) { logClusters[i] = k + firstGlyphIndex; outAttributes[k].clusterStart = true; ++k; @@ -308,7 +336,7 @@ bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLay : QFixed::fromReal(lastGlyphAdvance.width); if (endWithPDF) { - logClusters[stringRange.location + stringRange.length - 1] = glyphCount; + logClusters[stringRange.location + stringRange.length - 1] = glyphCount + prepend; outGlyphs[glyphCount] = 0xFFFF; outAdvances_x[glyphCount] = 0; outAdvances_y[glyphCount] = 0; @@ -837,6 +865,15 @@ QFixed QCoreTextFontEngine::emSquareSize() const return QFixed::QFixed(int(CTFontGetUnitsPerEm(ctfont))); } +QFontEngine *QCoreTextFontEngine::cloneWithSize(qreal pixelSize) const +{ + QFontDef newFontDef = fontDef; + newFontDef.pixelSize = pixelSize; + newFontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi(); + + return new QCoreTextFontEngine(cgFont, newFontDef); +} + QT_END_NAMESPACE #endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) diff --git a/src/gui/text/qfontengine_coretext_p.h b/src/gui/text/qfontengine_coretext_p.h index 1503c3f..3775bc6 100644 --- a/src/gui/text/qfontengine_coretext_p.h +++ b/src/gui/text/qfontengine_coretext_p.h @@ -91,6 +91,8 @@ public: virtual qreal minLeftBearing() const; virtual QFixed emSquareSize() const; + virtual QFontEngine *cloneWithSize(qreal pixelSize) const; + private: friend class QRawFontPrivate; @@ -118,9 +120,12 @@ public: QTextEngine::ShaperFlags flags) const; bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, - unsigned short *logClusters, const HB_CharAttributes *charAttributes) const; + unsigned short *logClusters, const HB_CharAttributes *charAttributes, + QScriptItem *si) const; virtual const char *name() const { return "CoreText"; } + inline CTFontRef macFontID() const { return ctfont; } + protected: virtual void loadEngine(int at); diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp index 8f2da9b..9d4a21a 100644 --- a/src/gui/text/qfontengine_ft.cpp +++ b/src/gui/text/qfontengine_ft.cpp @@ -803,106 +803,6 @@ int QFontEngineFT::loadFlags(QGlyphSet *set, GlyphFormat format, int flags, return load_flags; } -QFontEngineFT::Glyph *QFontEngineFT::loadGlyphMetrics(QGlyphSet *set, uint glyph, GlyphFormat format) const -{ - Glyph *g = set->getGlyph(glyph); - if (g && g->format == format) - return g; - - bool hsubpixel = false; - int vfactor = 1; - int load_flags = loadFlags(set, format, 0, hsubpixel, vfactor); - - // apply our matrix to this, but note that the metrics will not be affected by this. - FT_Face face = lockFace(); - FT_Matrix matrix = this->matrix; - FT_Matrix_Multiply(&set->transformationMatrix, &matrix); - FT_Set_Transform(face, &matrix, 0); - freetype->matrix = matrix; - - bool transform = matrix.xx != 0x10000 || matrix.yy != 0x10000 || matrix.xy != 0 || matrix.yx != 0; - if (transform) - load_flags |= FT_LOAD_NO_BITMAP; - - FT_Error err = FT_Load_Glyph(face, glyph, load_flags); - if (err && (load_flags & FT_LOAD_NO_BITMAP)) { - load_flags &= ~FT_LOAD_NO_BITMAP; - err = FT_Load_Glyph(face, glyph, load_flags); - } - if (err == FT_Err_Too_Few_Arguments) { - // this is an error in the bytecode interpreter, just try to run without it - load_flags |= FT_LOAD_FORCE_AUTOHINT; - err = FT_Load_Glyph(face, glyph, load_flags); - } - if (err != FT_Err_Ok) - qWarning("load glyph failed err=%x face=%p, glyph=%d", err, face, glyph); - - unlockFace(); - if (set->outline_drawing) - return 0; - - if (!g) { - g = new Glyph; - g->uploadedToServer = false; - g->data = 0; - } - - FT_GlyphSlot slot = face->glyph; - if (embolden) Q_FT_GLYPHSLOT_EMBOLDEN(slot); - int left = slot->metrics.horiBearingX; - int right = slot->metrics.horiBearingX + slot->metrics.width; - int top = slot->metrics.horiBearingY; - int bottom = slot->metrics.horiBearingY - slot->metrics.height; - if (transform && slot->format != FT_GLYPH_FORMAT_BITMAP) { // freetype doesn't apply the transformation on the metrics - int l, r, t, b; - FT_Vector vector; - vector.x = left; - vector.y = top; - FT_Vector_Transform(&vector, &matrix); - l = r = vector.x; - t = b = vector.y; - vector.x = right; - vector.y = top; - FT_Vector_Transform(&vector, &matrix); - if (l > vector.x) l = vector.x; - if (r < vector.x) r = vector.x; - if (t < vector.y) t = vector.y; - if (b > vector.y) b = vector.y; - vector.x = right; - vector.y = bottom; - FT_Vector_Transform(&vector, &matrix); - if (l > vector.x) l = vector.x; - if (r < vector.x) r = vector.x; - if (t < vector.y) t = vector.y; - if (b > vector.y) b = vector.y; - vector.x = left; - vector.y = bottom; - FT_Vector_Transform(&vector, &matrix); - if (l > vector.x) l = vector.x; - if (r < vector.x) r = vector.x; - if (t < vector.y) t = vector.y; - if (b > vector.y) b = vector.y; - left = l; - right = r; - top = t; - bottom = b; - } - left = FLOOR(left); - right = CEIL(right); - bottom = FLOOR(bottom); - top = CEIL(top); - - g->linearAdvance = face->glyph->linearHoriAdvance >> 10; - g->width = TRUNC(right-left); - g->height = TRUNC(top-bottom); - g->x = TRUNC(left); - g->y = TRUNC(top); - g->advance = TRUNC(ROUND(face->glyph->advance.x)); - g->format = Format_None; - - return g; -} - QFontEngineFT::Glyph *QFontEngineFT::loadGlyph(QGlyphSet *set, uint glyph, QFixed subPixelPosition, GlyphFormat format, @@ -1697,7 +1597,7 @@ void QFontEngineFT::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlag FT_Face face = 0; bool design = (default_hint_style == HintNone || default_hint_style == HintLight || - (flags & HB_ShaperFlag_UseDesignMetrics)); + (flags & HB_ShaperFlag_UseDesignMetrics)) && FT_IS_SCALABLE(freetype->face); for (int i = 0; i < glyphs->numGlyphs; i++) { Glyph *g = defaultGlyphSet.getGlyph(glyphs->glyphs[i]); if (g) { @@ -1851,6 +1751,7 @@ glyph_metrics_t QFontEngineFT::alphaMapBoundingBox(glyph_t glyph, QFixed subPixe } else { glyphSet = &defaultGlyphSet; } + bool needsDelete = false; Glyph * g = glyphSet->getGlyph(glyph); if (!g || g->format != format) { face = lockFace(); @@ -1858,6 +1759,7 @@ glyph_metrics_t QFontEngineFT::alphaMapBoundingBox(glyph_t glyph, QFixed subPixe FT_Matrix_Multiply(&glyphSet->transformationMatrix, &m); freetype->matrix = m; g = loadGlyph(glyphSet, glyph, subPixelPosition, format); + needsDelete = true; } if (g) { @@ -1866,6 +1768,8 @@ glyph_metrics_t QFontEngineFT::alphaMapBoundingBox(glyph_t glyph, QFixed subPixe overall.width = g->width; overall.height = g->height; overall.xoff = g->advance; + if (needsDelete) + delete g; } else { int left = FLOOR(face->glyph->metrics.horiBearingX); int right = CEIL(face->glyph->metrics.horiBearingX + face->glyph->metrics.width); @@ -2069,6 +1973,41 @@ HB_Error QFontEngineFT::getPointInOutline(HB_Glyph glyph, int flags, hb_uint32 p return result; } +bool QFontEngineFT::initFromFontEngine(const QFontEngineFT *fe) +{ + if (!init(fe->faceId(), fe->antialias, fe->defaultFormat, fe->freetype)) + return false; + + // Increase the reference of this QFreetypeFace since one more QFontEngineFT + // will be using it + freetype->ref.ref(); + + default_load_flags = fe->default_load_flags; + default_hint_style = fe->default_hint_style; + antialias = fe->antialias; + transform = fe->transform; + embolden = fe->embolden; + subpixelType = fe->subpixelType; + lcdFilterType = fe->lcdFilterType; + canUploadGlyphsToServer = fe->canUploadGlyphsToServer; + embeddedbitmap = fe->embeddedbitmap; + + return true; +} + +QFontEngine *QFontEngineFT::cloneWithSize(qreal pixelSize) const +{ + QFontDef fontDef; + fontDef.pixelSize = pixelSize; + QFontEngineFT *fe = new QFontEngineFT(fontDef); + if (!fe->initFromFontEngine(this)) { + delete fe; + return 0; + } else { + return fe; + } +} + QT_END_NAMESPACE #endif // QT_NO_FREETYPE diff --git a/src/gui/text/qfontengine_ft_p.h b/src/gui/text/qfontengine_ft_p.h index 887efed..a620006 100644 --- a/src/gui/text/qfontengine_ft_p.h +++ b/src/gui/text/qfontengine_ft_p.h @@ -122,7 +122,7 @@ struct QFreetypeFace static void addBitmapToPath(FT_GlyphSlot slot, const QFixedPoint &point, QPainterPath *path, bool = false); private: - friend class QFontEngineFTRawFont; + friend class QFontEngineFT; friend class QScopedPointerDeleter<QFreetypeFace>; QFreetypeFace() : _lock(QMutex::Recursive) {} ~QFreetypeFace() {} @@ -319,6 +319,10 @@ private: }; void setDefaultHintStyle(HintStyle style); + + virtual QFontEngine *cloneWithSize(qreal pixelSize) const; + bool initFromFontEngine(const QFontEngineFT *fontEngine); + HintStyle defaultHintStyle() const { return default_hint_style; } protected: @@ -345,7 +349,6 @@ protected: private: friend class QFontEngineFTRawFont; - QFontEngineFT::Glyph *loadGlyphMetrics(QGlyphSet *set, uint glyph, GlyphFormat format) const; int loadFlags(QGlyphSet *set, GlyphFormat format, int flags, bool &hsubpixel, int &vfactor) const; GlyphFormat defaultFormat; diff --git a/src/gui/text/qfontengine_mac.mm b/src/gui/text/qfontengine_mac.mm index 673a7c8..9f094ad 100644 --- a/src/gui/text/qfontengine_mac.mm +++ b/src/gui/text/qfontengine_mac.mm @@ -377,7 +377,7 @@ bool QFontEngineMacMulti::stringToCMap(const QChar *str, int len, QGlyphLayout * } bool QFontEngineMacMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, - unsigned short *logClusters, const HB_CharAttributes *charAttributes) const + unsigned short *logClusters, const HB_CharAttributes *charAttributes, QScriptItem *) const { if (*nglyphs < len) { *nglyphs = len; diff --git a/src/gui/text/qfontengine_mac_p.h b/src/gui/text/qfontengine_mac_p.h index 385fa83..292ea98 100644 --- a/src/gui/text/qfontengine_mac_p.h +++ b/src/gui/text/qfontengine_mac_p.h @@ -131,7 +131,7 @@ public: virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, - unsigned short *logClusters, const HB_CharAttributes *charAttributes) const; + unsigned short *logClusters, const HB_CharAttributes *charAttributes, QScriptItem *) const; virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const; diff --git a/src/gui/text/qfontengine_p.h b/src/gui/text/qfontengine_p.h index 5b39fd3..6db0aa6 100644 --- a/src/gui/text/qfontengine_p.h +++ b/src/gui/text/qfontengine_p.h @@ -235,6 +235,8 @@ public: virtual int glyphCount() const; + virtual QFontEngine *cloneWithSize(qreal /*pixelSize*/) const { return 0; } + HB_Font harfbuzzFont() const; HB_Face harfbuzzFace() const; diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp index 82d9da0..54d7ec2 100644 --- a/src/gui/text/qfontengine_win.cpp +++ b/src/gui/text/qfontengine_win.cpp @@ -1284,6 +1284,23 @@ QImage QFontEngineWin::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, co return rgbMask; } +// From qfontdatabase_win.cpp +extern QFontEngine *qt_load_font_engine_win(const QFontDef &request); +QFontEngine *QFontEngineWin::cloneWithSize(qreal pixelSize) const +{ + QFontDef request = fontDef; + QString actualFontName = request.family; + if (!uniqueFamilyName.isEmpty()) + request.family = uniqueFamilyName; + request.pixelSize = pixelSize; + + QFontEngine *fontEngine = qt_load_font_engine_win(request); + if (fontEngine != NULL) + fontEngine->fontDef.family = actualFontName; + + return fontEngine; +} + // -------------------------------------- Multi font engine QFontEngineMultiWin::QFontEngineMultiWin(QFontEngine *first, const QStringList &fallbacks) diff --git a/src/gui/text/qfontengine_win_p.h b/src/gui/text/qfontengine_win_p.h index 28d8000..114149d 100644 --- a/src/gui/text/qfontengine_win_p.h +++ b/src/gui/text/qfontengine_win_p.h @@ -106,6 +106,8 @@ public: virtual QImage alphaMapForGlyph(glyph_t, const QTransform &xform); virtual QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform); + virtual QFontEngine *cloneWithSize(qreal pixelSize) const; + #ifndef Q_CC_MINGW virtual void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0); #endif @@ -118,6 +120,7 @@ public: #endif QString _name; + QString uniqueFamilyName; HFONT hfont; LOGFONT logfont; uint stockFont : 1; diff --git a/src/gui/text/qfontengine_x11.cpp b/src/gui/text/qfontengine_x11.cpp index 9f3f8d3..4260b85 100644 --- a/src/gui/text/qfontengine_x11.cpp +++ b/src/gui/text/qfontengine_x11.cpp @@ -1196,6 +1196,20 @@ bool QFontEngineX11FT::uploadGlyphToServer(QGlyphSet *set, uint glyphid, Glyph * #endif } +QFontEngine *QFontEngineX11FT::cloneWithSize(qreal pixelSize) const +{ + QFontDef fontDef; + fontDef.pixelSize = pixelSize; + QFontEngineX11FT *fe = new QFontEngineX11FT(fontDef); + if (!fe->initFromFontEngine(this)) { + delete fe; + return 0; + } else { + fe->xglyph_format = xglyph_format; + return fe; + } +} + #endif // QT_NO_FONTCONFIG QT_END_NAMESPACE diff --git a/src/gui/text/qfontengine_x11_p.h b/src/gui/text/qfontengine_x11_p.h index ad68fac..d7eb39d 100644 --- a/src/gui/text/qfontengine_x11_p.h +++ b/src/gui/text/qfontengine_x11_p.h @@ -161,6 +161,8 @@ public: explicit QFontEngineX11FT(FcPattern *pattern, const QFontDef &fd, int screen); ~QFontEngineX11FT(); + QFontEngine *cloneWithSize(qreal pixelSize) const; + #ifndef QT_NO_XRENDER int xglyph_format; #endif diff --git a/src/gui/text/qfontenginedirectwrite.cpp b/src/gui/text/qfontenginedirectwrite.cpp index f0a3644..aab00c0 100644 --- a/src/gui/text/qfontenginedirectwrite.cpp +++ b/src/gui/text/qfontenginedirectwrite.cpp @@ -630,6 +630,17 @@ QFontEngine::Type QFontEngineDirectWrite::type() const return QFontEngine::DirectWrite; } +QFontEngine *QFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const +{ + QFontEngine *fontEngine = new QFontEngineDirectWrite(m_directWriteFactory, m_directWriteFontFace, + pixelSize); + + fontEngine->fontDef = fontDef; + fontEngine->fontDef.pixelSize = pixelSize; + + return fontEngine; +} + QT_END_NAMESPACE #endif // QT_NO_DIRECTWRITE diff --git a/src/gui/text/qfontenginedirectwrite_p.h b/src/gui/text/qfontenginedirectwrite_p.h index c440a6c..53a4b0a 100644 --- a/src/gui/text/qfontenginedirectwrite_p.h +++ b/src/gui/text/qfontenginedirectwrite_p.h @@ -101,6 +101,8 @@ public: QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform); + QFontEngine *cloneWithSize(qreal pixelSize) const; + bool canRender(const QChar *string, int len); Type type() const; diff --git a/src/gui/text/qglyphs.cpp b/src/gui/text/qglyphrun.cpp index b8a418d..ea52788 100644 --- a/src/gui/text/qglyphs.cpp +++ b/src/gui/text/qglyphrun.cpp @@ -43,14 +43,14 @@ #if !defined(QT_NO_RAWFONT) -#include "qglyphs.h" -#include "qglyphs_p.h" +#include "qglyphrun.h" +#include "qglyphrun_p.h" QT_BEGIN_NAMESPACE /*! - \class QGlyphs - \brief the QGlyphs class provides direct access to the internal glyphs in a font + \class QGlyphRun + \brief The QGlyphRun class provides direct access to the internal glyphs in a font. \since 4.8 \ingroup text @@ -67,42 +67,43 @@ QT_BEGIN_NAMESPACE Under certain circumstances, it can be useful as an application developer to have more low-level control over which glyphs in a specific font are drawn to the screen. This could for instance be the case in applications that use an external font engine and text shaper together with Qt. - QGlyphs provides an interface to the raw data needed to get text on the screen. It + QGlyphRun provides an interface to the raw data needed to get text on the screen. It contains a list of glyph indexes, a position for each glyph and a font. It is the user's responsibility to ensure that the selected font actually contains the provided glyph indexes. - QTextLayout::glyphs() or QTextFragment::glyphs() can be used to convert unicode encoded text - into a list of QGlyphs objects, and QPainter::drawGlyphs() can be used to draw the glyphs. + QTextLayout::glyphRuns() or QTextFragment::glyphRuns() can be used to convert unicode encoded + text into a list of QGlyphRun objects, and QPainter::drawGlyphRun() can be used to draw the + glyphs. - \note Please note that QRawFont is considered local to the thread in which it is constructed, - which in turn means that a new QRawFont will have to be created and set on the QGlyphs if it is - moved to a different thread. If the QGlyphs contains a reference to a QRawFont from a different + \note Please note that QRawFont is considered local to the thread in which it is constructed. + This in turn means that a new QRawFont will have to be created and set on the QGlyphRun if it is + moved to a different thread. If the QGlyphRun contains a reference to a QRawFont from a different thread than the current, it will not be possible to draw the glyphs using a QPainter, as the QRawFont is considered invalid and inaccessible in this case. */ /*! - Constructs an empty QGlyphs object. + Constructs an empty QGlyphRun object. */ -QGlyphs::QGlyphs() : d(new QGlyphsPrivate) +QGlyphRun::QGlyphRun() : d(new QGlyphRunPrivate) { } /*! - Constructs a QGlyphs object which is a copy of \a other. + Constructs a QGlyphRun object which is a copy of \a other. */ -QGlyphs::QGlyphs(const QGlyphs &other) +QGlyphRun::QGlyphRun(const QGlyphRun &other) { d = other.d; } /*! - Destroys the QGlyphs. + Destroys the QGlyphRun. */ -QGlyphs::~QGlyphs() +QGlyphRun::~QGlyphRun() { // Required for QExplicitlySharedDataPointer } @@ -110,26 +111,26 @@ QGlyphs::~QGlyphs() /*! \internal */ -void QGlyphs::detach() +void QGlyphRun::detach() { if (d->ref != 1) d.detach(); } /*! - Assigns \a other to this QGlyphs object. + Assigns \a other to this QGlyphRun object. */ -QGlyphs &QGlyphs::operator=(const QGlyphs &other) +QGlyphRun &QGlyphRun::operator=(const QGlyphRun &other) { d = other.d; return *this; } /*! - Compares \a other to this QGlyphs object. Returns true if the list of glyph indexes, + Compares \a other to this QGlyphRun object. Returns true if the list of glyph indexes, the list of positions and the font are all equal, otherwise returns false. */ -bool QGlyphs::operator==(const QGlyphs &other) const +bool QGlyphRun::operator==(const QGlyphRun &other) const { return ((d == other.d) || (d->glyphIndexes == other.d->glyphIndexes @@ -137,14 +138,14 @@ bool QGlyphs::operator==(const QGlyphs &other) const && d->overline == other.d->overline && d->underline == other.d->underline && d->strikeOut == other.d->strikeOut - && d->font == other.d->font)); + && d->rawFont == other.d->rawFont)); } /*! - Compares \a other to this QGlyphs object. Returns true if any of the list of glyph + Compares \a other to this QGlyphRun object. Returns true if any of the list of glyph indexes, the list of positions or the font are different, otherwise returns false. */ -bool QGlyphs::operator!=(const QGlyphs &other) const +bool QGlyphRun::operator!=(const QGlyphRun &other) const { return !(*this == other); } @@ -152,13 +153,13 @@ bool QGlyphs::operator!=(const QGlyphs &other) const /*! \internal - Adds together the lists of glyph indexes and positions in \a other and this QGlyphs - object and returns the result. The font in the returned QGlyphs will be the same as in - this QGlyphs object. + Adds together the lists of glyph indexes and positions in \a other and this QGlyphRun + object and returns the result. The font in the returned QGlyphRun will be the same as in + this QGlyphRun object. */ -QGlyphs QGlyphs::operator+(const QGlyphs &other) const +QGlyphRun QGlyphRun::operator+(const QGlyphRun &other) const { - QGlyphs ret(*this); + QGlyphRun ret(*this); ret += other; return ret; } @@ -166,10 +167,10 @@ QGlyphs QGlyphs::operator+(const QGlyphs &other) const /*! \internal - Appends the glyph indexes and positions in \a other to this QGlyphs object and returns + Appends the glyph indexes and positions in \a other to this QGlyphRun object and returns a reference to the current object. */ -QGlyphs &QGlyphs::operator+=(const QGlyphs &other) +QGlyphRun &QGlyphRun::operator+=(const QGlyphRun &other) { detach(); @@ -180,41 +181,41 @@ QGlyphs &QGlyphs::operator+=(const QGlyphs &other) } /*! - Returns the font selected for this QGlyphs object. + Returns the font selected for this QGlyphRun object. - \sa setFont() + \sa setRawFont() */ -QRawFont QGlyphs::font() const +QRawFont QGlyphRun::rawFont() const { - return d->font; + return d->rawFont; } /*! Sets the font in which to look up the glyph indexes to \a font. - \sa font(), setGlyphIndexes() + \sa rawFont(), setGlyphIndexes() */ -void QGlyphs::setFont(const QRawFont &font) +void QGlyphRun::setRawFont(const QRawFont &rawFont) { detach(); - d->font = font; + d->rawFont = rawFont; } /*! - Returns the glyph indexes for this QGlyphs object. + Returns the glyph indexes for this QGlyphRun object. \sa setGlyphIndexes(), setPositions() */ -QVector<quint32> QGlyphs::glyphIndexes() const +QVector<quint32> QGlyphRun::glyphIndexes() const { return d->glyphIndexes; } /*! - Set the glyph indexes for this QGlyphs object to \a glyphIndexes. The glyph indexes must + Set the glyph indexes for this QGlyphRun object to \a glyphIndexes. The glyph indexes must be valid for the selected font. */ -void QGlyphs::setGlyphIndexes(const QVector<quint32> &glyphIndexes) +void QGlyphRun::setGlyphIndexes(const QVector<quint32> &glyphIndexes) { detach(); d->glyphIndexes = glyphIndexes; @@ -223,7 +224,7 @@ void QGlyphs::setGlyphIndexes(const QVector<quint32> &glyphIndexes) /*! Returns the position of the edge of the baseline for each glyph in this set of glyph indexes. */ -QVector<QPointF> QGlyphs::positions() const +QVector<QPointF> QGlyphRun::positions() const { return d->glyphPositions; } @@ -232,87 +233,87 @@ QVector<QPointF> QGlyphs::positions() const Sets the positions of the edge of the baseline for each glyph in this set of glyph indexes to \a positions. */ -void QGlyphs::setPositions(const QVector<QPointF> &positions) +void QGlyphRun::setPositions(const QVector<QPointF> &positions) { detach(); d->glyphPositions = positions; } /*! - Clears all data in the QGlyphs object. + Clears all data in the QGlyphRun object. */ -void QGlyphs::clear() +void QGlyphRun::clear() { detach(); d->glyphPositions = QVector<QPointF>(); d->glyphIndexes = QVector<quint32>(); - d->font = QRawFont(); + d->rawFont = QRawFont(); d->strikeOut = false; d->overline = false; d->underline = false; } /*! - Returns true if this QGlyphs should be painted with an overline decoration. + Returns true if this QGlyphRun should be painted with an overline decoration. \sa setOverline() */ -bool QGlyphs::overline() const +bool QGlyphRun::overline() const { return d->overline; } /*! - Indicates that this QGlyphs should be painted with an overline decoration if \a overline is true. - Otherwise the QGlyphs should be painted with no overline decoration. + Indicates that this QGlyphRun should be painted with an overline decoration if \a overline is true. + Otherwise the QGlyphRun should be painted with no overline decoration. \sa overline() */ -void QGlyphs::setOverline(bool overline) +void QGlyphRun::setOverline(bool overline) { detach(); d->overline = overline; } /*! - Returns true if this QGlyphs should be painted with an underline decoration. + Returns true if this QGlyphRun should be painted with an underline decoration. \sa setUnderline() */ -bool QGlyphs::underline() const +bool QGlyphRun::underline() const { return d->underline; } /*! - Indicates that this QGlyphs should be painted with an underline decoration if \a underline is - true. Otherwise the QGlyphs should be painted with no underline decoration. + Indicates that this QGlyphRun should be painted with an underline decoration if \a underline is + true. Otherwise the QGlyphRun should be painted with no underline decoration. \sa underline() */ -void QGlyphs::setUnderline(bool underline) +void QGlyphRun::setUnderline(bool underline) { detach(); d->underline = underline; } /*! - Returns true if this QGlyphs should be painted with a strike out decoration. + Returns true if this QGlyphRun should be painted with a strike out decoration. \sa setStrikeOut() */ -bool QGlyphs::strikeOut() const +bool QGlyphRun::strikeOut() const { return d->strikeOut; } /*! - Indicates that this QGlyphs should be painted with an strike out decoration if \a strikeOut is - true. Otherwise the QGlyphs should be painted with no strike out decoration. + Indicates that this QGlyphRun should be painted with an strike out decoration if \a strikeOut is + true. Otherwise the QGlyphRun should be painted with no strike out decoration. \sa strikeOut() */ -void QGlyphs::setStrikeOut(bool strikeOut) +void QGlyphRun::setStrikeOut(bool strikeOut) { detach(); d->strikeOut = strikeOut; diff --git a/src/gui/text/qglyphs.h b/src/gui/text/qglyphrun.h index 4d7dcaf..dcc166e 100644 --- a/src/gui/text/qglyphs.h +++ b/src/gui/text/qglyphrun.h @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#ifndef QGLYPHS_H -#define QGLYPHS_H +#ifndef QGLYPHRUN_H +#define QGLYPHRUN_H #include <QtCore/qsharedpointer.h> #include <QtCore/qvector.h> @@ -55,16 +55,16 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) -class QGlyphsPrivate; -class Q_GUI_EXPORT QGlyphs +class QGlyphRunPrivate; +class Q_GUI_EXPORT QGlyphRun { public: - QGlyphs(); - QGlyphs(const QGlyphs &other); - ~QGlyphs(); + QGlyphRun(); + QGlyphRun(const QGlyphRun &other); + ~QGlyphRun(); - QRawFont font() const; - void setFont(const QRawFont &font); + QRawFont rawFont() const; + void setRawFont(const QRawFont &rawFont); QVector<quint32> glyphIndexes() const; void setGlyphIndexes(const QVector<quint32> &glyphIndexes); @@ -74,9 +74,9 @@ public: void clear(); - QGlyphs &operator=(const QGlyphs &other); - bool operator==(const QGlyphs &other) const; - bool operator!=(const QGlyphs &other) const; + QGlyphRun &operator=(const QGlyphRun &other); + bool operator==(const QGlyphRun &other) const; + bool operator!=(const QGlyphRun &other) const; void setOverline(bool overline); bool overline() const; @@ -88,14 +88,14 @@ public: bool strikeOut() const; private: - friend class QGlyphsPrivate; + friend class QGlyphRunPrivate; friend class QTextLine; - QGlyphs operator+(const QGlyphs &other) const; - QGlyphs &operator+=(const QGlyphs &other); + QGlyphRun operator+(const QGlyphRun &other) const; + QGlyphRun &operator+=(const QGlyphRun &other); void detach(); - QExplicitlySharedDataPointer<QGlyphsPrivate> d; + QExplicitlySharedDataPointer<QGlyphRunPrivate> d; }; QT_END_NAMESPACE diff --git a/src/gui/text/qglyphs_p.h b/src/gui/text/qglyphrun_p.h index 944f777..4aa01d6 100644 --- a/src/gui/text/qglyphs_p.h +++ b/src/gui/text/qglyphrun_p.h @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#ifndef QGLYPHS_P_H -#define QGLYPHS_P_H +#ifndef QGLYPHRUN_P_H +#define QGLYPHRUN_P_H // // W A R N I N G @@ -53,7 +53,7 @@ // We mean it. // -#include "qglyphs.h" +#include "qglyphrun.h" #include "qrawfont.h" #include <qfont.h> @@ -64,21 +64,21 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -class QGlyphsPrivate: public QSharedData +class QGlyphRunPrivate: public QSharedData { public: - QGlyphsPrivate() + QGlyphRunPrivate() : overline(false) , underline(false) , strikeOut(false) { } - QGlyphsPrivate(const QGlyphsPrivate &other) + QGlyphRunPrivate(const QGlyphRunPrivate &other) : QSharedData(other) , glyphIndexes(other.glyphIndexes) , glyphPositions(other.glyphPositions) - , font(other.font) + , rawFont(other.rawFont) , overline(other.overline) , underline(other.underline) , strikeOut(other.strikeOut) @@ -87,7 +87,7 @@ public: QVector<quint32> glyphIndexes; QVector<QPointF> glyphPositions; - QRawFont font; + QRawFont rawFont; uint overline : 1; uint underline : 1; diff --git a/src/gui/text/qplatformfontdatabase_qpa.cpp b/src/gui/text/qplatformfontdatabase_qpa.cpp index 6fa25e7..82ec279 100644 --- a/src/gui/text/qplatformfontdatabase_qpa.cpp +++ b/src/gui/text/qplatformfontdatabase_qpa.cpp @@ -218,6 +218,16 @@ QFontEngine *QPlatformFontDatabase::fontEngine(const QFontDef &fontDef, QUnicode return engine; } +QFontEngine *QPlatformFontDatabase::fontEngine(const QByteArray &fontData, qreal pixelSize, + QFont::HintingPreference hintingPreference) +{ + Q_UNUSED(fontData); + Q_UNUSED(pixelSize); + Q_UNUSED(hintingPreference); + qWarning("This plugin does not support font engines created directly from font data"); + return 0; +} + /*! */ diff --git a/src/gui/text/qplatformfontdatabase_qpa.h b/src/gui/text/qplatformfontdatabase_qpa.h index e0e4f04..046311f 100644 --- a/src/gui/text/qplatformfontdatabase_qpa.h +++ b/src/gui/text/qplatformfontdatabase_qpa.h @@ -92,6 +92,8 @@ public: virtual QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName); virtual void releaseHandle(void *handle); + virtual QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference); + virtual QString fontDir() const; //callback diff --git a/src/gui/text/qrawfont.cpp b/src/gui/text/qrawfont.cpp index 4a715c2..44ddfd2 100644 --- a/src/gui/text/qrawfont.cpp +++ b/src/gui/text/qrawfont.cpp @@ -78,7 +78,7 @@ QT_BEGIN_NAMESPACE A QRawFont object represents a single, physical instance of a given font in a given pixel size. I.e. in the typical case it represents a set of TrueType or OpenType font tables and uses a user specified pixel size to convert metrics into logical pixel units. In can be used in - combination with the QGlyphs class to draw specific glyph indexes at specific positions, and + combination with the QGlyphRun class to draw specific glyph indexes at specific positions, and also have accessors to some relevant data in the physical font. QRawFont only provides support for the main font technologies: GDI and DirectWrite on Windows @@ -87,9 +87,9 @@ QT_BEGIN_NAMESPACE QRawFont can be constructed in a number of ways: \list - \o \l It can be constructed by calling QTextLayout::glyphs() or QTextFragment::glyphs(). The - returned QGlyphs objects will contain QRawFont objects which represent the actual fonts - used to render each portion of the text. + \o \l It can be constructed by calling QTextLayout::glyphRuns() or QTextFragment::glyphRuns(). + The returned QGlyphRun objects will contain QRawFont objects which represent the actual + fonts used to render each portion of the text. \o \l It can be constructed by passing a QFont object to QRawFont::fromFont(). The function will return a QRawFont object representing the font that will be selected as response to the QFont query and the selected writing system. @@ -234,7 +234,7 @@ void QRawFont::loadFromData(const QByteArray &fontData, the pixel in the rasterization of the glyph. Otherwise, the image will be in the format of QImage::Format_A8 and each pixel will contain the opacity of the pixel in the rasterization. - \sa pathForGlyph(), QPainter::drawGlyphs() + \sa pathForGlyph(), QPainter::drawGlyphRun() */ QImage QRawFont::alphaMapForGlyph(quint32 glyphIndex, AntialiasingType antialiasingType, const QTransform &transform) const @@ -302,16 +302,68 @@ qreal QRawFont::descent() const } /*! + Returns the xHeight of this QRawFont in pixel units. + + \sa QFontMetricsF::xHeight() +*/ +qreal QRawFont::xHeight() const +{ + if (!isValid()) + return 0.0; + + return d->fontEngine->xHeight().toReal(); +} + +/*! + Returns the leading of this QRawFont in pixel units. + + \sa QFontMetricsF::leading() +*/ +qreal QRawFont::leading() const +{ + if (!isValid()) + return 0.0; + + return d->fontEngine->leading().toReal(); +} + +/*! + Returns the average character width of this QRawFont in pixel units. + + \sa QFontMetricsF::averageCharWidth() +*/ +qreal QRawFont::averageCharWidth() const +{ + if (!isValid()) + return 0.0; + + return d->fontEngine->averageCharWidth().toReal(); +} + +/*! + Returns the width of the widest character in the font. + + \sa QFontMetricsF::maxWidth() +*/ +qreal QRawFont::maxCharWidth() const +{ + if (!isValid()) + return 0.0; + + return d->fontEngine->maxCharWidth(); +} + +/*! Returns the pixel size set for this QRawFont. The pixel size affects how glyphs are rasterized, the size of glyphs returned by pathForGlyph(), and is used to convert internal metrics from design units to logical pixel units. \sa setPixelSize() */ -int QRawFont::pixelSize() const +qreal QRawFont::pixelSize() const { if (!isValid()) - return -1; + return 0.0; return d->fontEngine->fontDef.pixelSize; } @@ -374,9 +426,9 @@ int QRawFont::weight() const underlying font. Note that in cases where there are other tables in the font that affect the shaping of the text, the returned glyph indexes will not correctly represent the rendering of the text. To get the correctly shaped text, you can use QTextLayout to lay out and shape the - text, and then call QTextLayout::glyphs() to get the set of glyph index list and QRawFont pairs. + text, and then call QTextLayout::glyphRuns() to get the set of glyph index list and QRawFont pairs. - \sa advancesForGlyphIndexes(), QGlyphs, QTextLayout::glyphs(), QTextFragment::glyphs() + \sa advancesForGlyphIndexes(), glyphIndexesForChars(), QGlyphRun, QTextLayout::glyphRuns(), QTextFragment::glyphRuns() */ QVector<quint32> QRawFont::glyphIndexesForString(const QString &text) const { @@ -385,11 +437,9 @@ QVector<quint32> QRawFont::glyphIndexesForString(const QString &text) const int nglyphs = text.size(); QVarLengthGlyphLayoutArray glyphs(nglyphs); - if (!d->fontEngine->stringToCMap(text.data(), text.size(), &glyphs, &nglyphs, - QTextEngine::GlyphIndicesOnly)) { + if (!glyphIndexesForChars(text.data(), text.size(), glyphs.glyphs, &nglyphs)) { glyphs.resize(nglyphs); - if (!d->fontEngine->stringToCMap(text.data(), text.size(), &glyphs, &nglyphs, - QTextEngine::GlyphIndicesOnly)) { + if (!glyphIndexesForChars(text.data(), text.size(), glyphs.glyphs, &nglyphs)) { Q_ASSERT_X(false, Q_FUNC_INFO, "stringToCMap shouldn't fail twice"); return QVector<quint32>(); } @@ -403,6 +453,26 @@ QVector<quint32> QRawFont::glyphIndexesForString(const QString &text) const } /*! + Converts a string of unicode points to glyph indexes using the CMAP table in the + underlying font. The function works like glyphIndexesForString() except it take + an array (\a chars), the results will be returned though \a glyphIndexes array + and number of glyphs will be set in \a numGlyphs. The size of \a glyphIndexes array + must be at least \a numChars, if that's still not enough, this function will return + false, then you can resize \a glyphIndexes from the size returned in \a numGlyphs. + + \sa glyphIndexesForString(), advancesForGlyphIndexes(), QGlyphs, QTextLayout::glyphs(), QTextFragment::glyphs() +*/ +bool QRawFont::glyphIndexesForChars(const QChar *chars, int numChars, quint32 *glyphIndexes, int *numGlyphs) const +{ + if (!isValid()) + return false; + + QGlyphLayout glyphs; + glyphs.glyphs = glyphIndexes; + return d->fontEngine->stringToCMap(chars, numChars, &glyphs, numGlyphs, QTextEngine::GlyphIndicesOnly); +} + +/*! Returns the QRawFont's advances for each of the \a glyphIndexes in pixel units. The advances give the distance from the position of a given glyph to where the next glyph should be drawn to make it appear as if the two glyphs are unspaced. @@ -428,6 +498,36 @@ QVector<QPointF> QRawFont::advancesForGlyphIndexes(const QVector<quint32> &glyph } /*! + Returns the QRawFont's advances for each of the \a glyphIndexes in pixel units. The advances + give the distance from the position of a given glyph to where the next glyph should be drawn + to make it appear as if the two glyphs are unspaced. The glyph indexes are given with the + array \a glyphIndexes while the results are returned through \a advances, both of them must + have \a numGlyphs elements. + + \sa QTextLine::horizontalAdvance(), QFontMetricsF::width() +*/ +bool QRawFont::advancesForGlyphIndexes(const quint32 *glyphIndexes, QPointF *advances, int numGlyphs) const +{ + if (!isValid()) + return false; + + QGlyphLayout glyphs; + glyphs.glyphs = const_cast<HB_Glyph *>(glyphIndexes); + glyphs.numGlyphs = numGlyphs; + QVarLengthArray<QFixed> advances_x(numGlyphs); + QVarLengthArray<QFixed> advances_y(numGlyphs); + glyphs.advances_x = advances_x.data(); + glyphs.advances_y = advances_y.data(); + + d->fontEngine->recalcAdvances(&glyphs, 0); + + for (int i=0; i<numGlyphs; ++i) + advances[i] = QPointF(glyphs.advances_x[i].toReal(), glyphs.advances_y[i].toReal()); + + return true; +} + +/*! Returns the hinting preference used to construct this QRawFont. \sa QFont::hintingPreference() @@ -535,17 +635,17 @@ QRawFont QRawFont::fromFont(const QFont &font, QFontDatabase::WritingSystem writ layout.beginLayout(); QTextLine line = layout.createLine(); layout.endLayout(); - QList<QGlyphs> list = layout.glyphs(); + QList<QGlyphRun> list = layout.glyphRuns(); if (list.size()) { // Pick the one matches the family name we originally requested, // if none of them match, just pick the first one for (int i = 0; i < list.size(); i++) { - QGlyphs glyphs = list.at(i); - QRawFont rawfont = glyphs.font(); + QGlyphRun glyphs = list.at(i); + QRawFont rawfont = glyphs.rawFont(); if (rawfont.familyName() == font.family()) return rawfont; } - return list.at(0).font(); + return list.at(0).rawFont(); } return QRawFont(); #else @@ -577,10 +677,21 @@ QRawFont QRawFont::fromFont(const QFont &font, QFontDatabase::WritingSystem writ /*! Sets the pixel size with which this font should be rendered to \a pixelSize. */ -void QRawFont::setPixelSize(int pixelSize) +void QRawFont::setPixelSize(qreal pixelSize) { + if (d->fontEngine == 0) + return; + detach(); - d->platformSetPixelSize(pixelSize); + QFontEngine *oldFontEngine = d->fontEngine; + + d->fontEngine = d->fontEngine->cloneWithSize(pixelSize); + if (d->fontEngine != 0) + d->fontEngine->ref.ref(); + + oldFontEngine->ref.deref(); + if (oldFontEngine->cache_count == 0 && oldFontEngine->ref == 0) + delete oldFontEngine; } /*! diff --git a/src/gui/text/qrawfont.h b/src/gui/text/qrawfont.h index 96dc838..3875fec 100644 --- a/src/gui/text/qrawfont.h +++ b/src/gui/text/qrawfont.h @@ -90,19 +90,25 @@ public: QVector<quint32> glyphIndexesForString(const QString &text) const; QVector<QPointF> advancesForGlyphIndexes(const QVector<quint32> &glyphIndexes) const; + bool glyphIndexesForChars(const QChar *chars, int numChars, quint32 *glyphIndexes, int *numGlyphs) const; + bool advancesForGlyphIndexes(const quint32 *glyphIndexes, QPointF *advances, int numGlyphs) const; QImage alphaMapForGlyph(quint32 glyphIndex, AntialiasingType antialiasingType = SubPixelAntialiasing, const QTransform &transform = QTransform()) const; QPainterPath pathForGlyph(quint32 glyphIndex) const; - void setPixelSize(int pixelSize); - int pixelSize() const; + void setPixelSize(qreal pixelSize); + qreal pixelSize() const; QFont::HintingPreference hintingPreference() const; qreal ascent() const; qreal descent() const; + qreal leading() const; + qreal xHeight() const; + qreal averageCharWidth() const; + qreal maxCharWidth() const; qreal unitsPerEm() const; diff --git a/src/gui/text/qrawfont_ft.cpp b/src/gui/text/qrawfont_ft.cpp index eefbd92..23d47eb 100644 --- a/src/gui/text/qrawfont_ft.cpp +++ b/src/gui/text/qrawfont_ft.cpp @@ -90,32 +90,6 @@ public: return init(faceId, true, Format_None, fontData); } - - bool initFromFontEngine(QFontEngine *oldFontEngine) - { - QFontEngineFT *fe = static_cast<QFontEngineFT *>(oldFontEngine); - - // Increase the reference of this QFreetypeFace since one more QFontEngineFT - // will be using it - fe->freetype->ref.ref(); - if (!init(fe->faceId(), fe->antialias, fe->defaultFormat, fe->freetype)) - return false; - - default_load_flags = fe->default_load_flags; - default_hint_style = fe->default_hint_style; - antialias = fe->antialias; - transform = fe->transform; - embolden = fe->embolden; - subpixelType = fe->subpixelType; - lcdFilterType = fe->lcdFilterType; - canUploadGlyphsToServer = fe->canUploadGlyphsToServer; - embeddedbitmap = fe->embeddedbitmap; - -#if defined(Q_WS_X11) - xglyph_format = static_cast<QFontEngineX11FT *>(fe)->xglyph_format; -#endif - return true; - } }; @@ -159,31 +133,6 @@ void QRawFontPrivate::platformLoadFromData(const QByteArray &fontData, int pixel fontEngine->ref.ref(); } -void QRawFontPrivate::platformSetPixelSize(int pixelSize) -{ - if (fontEngine == NULL) - return; - - QFontEngine *oldFontEngine = fontEngine; - - QFontDef fontDef; - fontDef.pixelSize = pixelSize; - QFontEngineFTRawFont *fe = new QFontEngineFTRawFont(fontDef); - if (!fe->initFromFontEngine(oldFontEngine)) { - delete fe; - return; - } - - fontEngine = fe; - fontEngine->fontDef = oldFontEngine->fontDef; - fontEngine->fontDef.pixelSize = pixelSize; - fontEngine->ref.ref(); - Q_ASSERT(fontEngine != oldFontEngine); - oldFontEngine->ref.deref(); - if (oldFontEngine->cache_count == 0 && oldFontEngine->ref == 0) - delete oldFontEngine; -} - QT_END_NAMESPACE #endif // QT_NO_RAWFONT diff --git a/src/gui/text/qrawfont_mac.cpp b/src/gui/text/qrawfont_mac.cpp index 56005c6..1ed4185 100644 --- a/src/gui/text/qrawfont_mac.cpp +++ b/src/gui/text/qrawfont_mac.cpp @@ -78,28 +78,6 @@ void QRawFontPrivate::platformLoadFromData(const QByteArray &fontData, } } -void QRawFontPrivate::platformSetPixelSize(int pixelSize) -{ - if (fontEngine == NULL) - return; - - QFontEngine *oldFontEngine = fontEngine; - - QFontDef fontDef = oldFontEngine->fontDef; - fontDef.pixelSize = pixelSize; - fontDef.pointSize = pixelSize * 72.0 / qt_defaultDpi(); - - QCoreTextFontEngine *ctFontEngine = static_cast<QCoreTextFontEngine *>(oldFontEngine); - Q_ASSERT(ctFontEngine->cgFont); - - fontEngine = new QCoreTextFontEngine(ctFontEngine->cgFont, fontDef); - fontEngine->ref.ref(); - Q_ASSERT(fontEngine != oldFontEngine); - oldFontEngine->ref.deref(); - if (oldFontEngine->cache_count == 0 && oldFontEngine->ref == 0) - delete oldFontEngine; -} - QT_END_NAMESPACE #endif // QT_NO_RAWFONT diff --git a/src/gui/text/qrawfont_p.h b/src/gui/text/qrawfont_p.h index f9a9ab5..e29ea9c 100644 --- a/src/gui/text/qrawfont_p.h +++ b/src/gui/text/qrawfont_p.h @@ -83,7 +83,6 @@ public: , fontHandle(NULL) , ptrAddFontMemResourceEx(other.ptrAddFontMemResourceEx) , ptrRemoveFontMemResourceEx(other.ptrRemoveFontMemResourceEx) - , uniqueFamilyName(other.uniqueFamilyName) #endif { fontEngine = other.fontEngine; @@ -102,7 +101,6 @@ public: void platformLoadFromData(const QByteArray &fontData, int pixelSize, QFont::HintingPreference hintingPreference); - void platformSetPixelSize(int pixelSize); static QRawFontPrivate *get(const QRawFont &font) { return font.d.data(); } @@ -120,8 +118,6 @@ public: PtrAddFontMemResourceEx ptrAddFontMemResourceEx; PtrRemoveFontMemResourceEx ptrRemoveFontMemResourceEx; - QString uniqueFamilyName; - #endif // Q_WS_WIN }; diff --git a/src/gui/util/qscroller_mac.mm b/src/gui/text/qrawfont_qpa.cpp index 4bf69c1..103619c 100644 --- a/src/gui/util/qscroller_mac.mm +++ b/src/gui/text/qrawfont_qpa.cpp @@ -41,31 +41,29 @@ #include <QtCore/qglobal.h> -#ifdef Q_WS_MAC +#if !defined(QT_NO_RAWFONT) -#import <Cocoa/Cocoa.h> +#include "qrawfont_p.h" +#include <QtGui/qplatformfontdatabase_qpa.h> +#include <private/qapplication_p.h> -#include "qscroller_p.h" +QT_BEGIN_NAMESPACE -QPointF QScrollerPrivate::realDpi(int screen) +void QRawFontPrivate::platformCleanUp() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSArray *nsscreens = [NSScreen screens]; - - if (screen < 0 || screen >= int([nsscreens count])) - screen = 0; +} - NSScreen *nsscreen = [nsscreens objectAtIndex:screen]; - CGDirectDisplayID display = [[[nsscreen deviceDescription] objectForKey:@"NSScreenNumber"] intValue]; +void QRawFontPrivate::platformLoadFromData(const QByteArray &fontData, int pixelSize, + QFont::HintingPreference hintingPreference) +{ + Q_ASSERT(fontEngine == 0); - CGSize mmsize = CGDisplayScreenSize(display); - if (mmsize.width > 0 && mmsize.height > 0) { - return QPointF(CGDisplayPixelsWide(display) / mmsize.width, - CGDisplayPixelsHigh(display) / mmsize.height) * qreal(25.4); - } else { - return QPointF(); - } - [pool release]; + QPlatformFontDatabase *pfdb = QApplicationPrivate::platformIntegration()->fontDatabase(); + fontEngine = pfdb->fontEngine(fontData, pixelSize, hintingPreference); + if (fontEngine != 0) + fontEngine->ref.ref(); } -#endif +QT_END_NAMESPACE + +#endif // QT_NO_RAWFONT diff --git a/src/gui/text/qrawfont_win.cpp b/src/gui/text/qrawfont_win.cpp index fb5c6f4..d8acf57 100644 --- a/src/gui/text/qrawfont_win.cpp +++ b/src/gui/text/qrawfont_win.cpp @@ -559,7 +559,7 @@ void QRawFontPrivate::platformLoadFromData(const QByteArray &_fontData, GUID guid; CoCreateGuid(&guid); - uniqueFamilyName = QString::fromLatin1("f") + QString uniqueFamilyName = QString::fromLatin1("f") + QString::number(guid.Data1, 36) + QLatin1Char('-') + QString::number(guid.Data2, 36) + QLatin1Char('-') + QString::number(guid.Data3, 36) + QLatin1Char('-') @@ -613,6 +613,7 @@ void QRawFontPrivate::platformLoadFromData(const QByteArray &_fontData, Q_ASSERT(fontEngine->cache_count == 0 && fontEngine->ref == 0); // Override the generated font name + static_cast<QFontEngineWin *>(fontEngine)->uniqueFamilyName = uniqueFamilyName; fontEngine->fontDef.family = actualFontName; fontEngine->ref.ref(); } @@ -701,50 +702,6 @@ void QRawFontPrivate::platformLoadFromData(const QByteArray &_fontData, } } -void QRawFontPrivate::platformSetPixelSize(int pixelSize) -{ - if (fontEngine == NULL) - return; - - QFontEngine *oldFontEngine = fontEngine; - -#if !defined(QT_NO_DIRECTWRITE) - if (fontEngine->type() == QFontEngine::Win) -#endif - - { - QFontDef request = fontEngine->fontDef; - QString actualFontName = request.family; - if (!uniqueFamilyName.isEmpty()) - request.family = uniqueFamilyName; - request.pixelSize = pixelSize; - - fontEngine = qt_load_font_engine_win(request); - if (fontEngine != NULL) { - fontEngine->fontDef.family = actualFontName; - fontEngine->ref.ref(); - } - } - -#if !defined(QT_NO_DIRECTWRITE) - else { - QFontEngineDirectWrite *dWriteFE = static_cast<QFontEngineDirectWrite *>(fontEngine); - fontEngine = new QFontEngineDirectWrite(dWriteFE->m_directWriteFactory, - dWriteFE->m_directWriteFontFace, - pixelSize); - - fontEngine->fontDef = dWriteFE->fontDef; - fontEngine->fontDef.pixelSize = pixelSize; - fontEngine->ref.ref(); - } -#endif - - Q_ASSERT(fontEngine != oldFontEngine); - oldFontEngine->ref.deref(); - if (oldFontEngine->cache_count == 0 && oldFontEngine->ref == 0) - delete oldFontEngine; -} - QT_END_NAMESPACE #endif // QT_NO_RAWFONT diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp index 4396730..a8bf763 100644 --- a/src/gui/text/qtextcontrol.cpp +++ b/src/gui/text/qtextcontrol.cpp @@ -677,7 +677,7 @@ void QTextControlPrivate::extendWordwiseSelection(int suggestedNewPosition, qrea const qreal wordEndX = line.cursorToX(curs.position() - blockPos) + blockCoordinates.x(); - if (mouseXPosition < wordStartX || mouseXPosition > wordEndX) + if (!wordSelectionEnabled && (mouseXPosition < wordStartX || mouseXPosition > wordEndX)) return; // keep the already selected word even when moving to the left @@ -1579,8 +1579,10 @@ void QTextControlPrivate::mousePressEvent(QEvent *e, Qt::MouseButton button, con emit q->cursorPositionChanged(); _q_updateCurrentCharFormatAndSelection(); } else { - if (cursor.position() != oldCursorPos) + if (cursor.position() != oldCursorPos) { emit q->cursorPositionChanged(); + emit q->microFocusChanged(); + } selectionChanged(); } repaintOldAndNewSelection(oldSelection); diff --git a/src/gui/text/qtextcursor.cpp b/src/gui/text/qtextcursor.cpp index 6ddfdb0..17bcc6c 100644 --- a/src/gui/text/qtextcursor.cpp +++ b/src/gui/text/qtextcursor.cpp @@ -362,20 +362,23 @@ bool QTextCursorPrivate::movePosition(QTextCursor::MoveOperation op, QTextCursor currentCharFormat = -1; bool adjustX = true; QTextBlock blockIt = block(); + bool visualMovement = priv->defaultCursorMoveStyle == Qt::VisualMoveStyle; if (!blockIt.isValid()) return false; - if (op >= QTextCursor::Left && op <= QTextCursor::WordRight - && blockIt.textDirection() == Qt::RightToLeft) { - if (op == QTextCursor::Left) - op = QTextCursor::NextCharacter; - else if (op == QTextCursor::Right) - op = QTextCursor::PreviousCharacter; - else if (op == QTextCursor::WordLeft) + if (blockIt.textDirection() == Qt::RightToLeft) { + if (op == QTextCursor::WordLeft) op = QTextCursor::NextWord; else if (op == QTextCursor::WordRight) op = QTextCursor::PreviousWord; + + if (!visualMovement) { + if (op == QTextCursor::Left) + op = QTextCursor::NextCharacter; + else if (op == QTextCursor::Right) + op = QTextCursor::PreviousCharacter; + } } const QTextLayout *layout = blockLayout(blockIt); @@ -418,9 +421,12 @@ bool QTextCursorPrivate::movePosition(QTextCursor::MoveOperation op, QTextCursor break; } case QTextCursor::PreviousCharacter: - case QTextCursor::Left: newPosition = priv->previousCursorPosition(position, QTextLayout::SkipCharacters); break; + case QTextCursor::Left: + newPosition = visualMovement ? priv->leftCursorPosition(position) + : priv->previousCursorPosition(position, QTextLayout::SkipCharacters); + break; case QTextCursor::StartOfWord: { if (relativePos == 0) break; @@ -529,9 +535,12 @@ bool QTextCursorPrivate::movePosition(QTextCursor::MoveOperation op, QTextCursor break; } case QTextCursor::NextCharacter: - case QTextCursor::Right: newPosition = priv->nextCursorPosition(position, QTextLayout::SkipCharacters); break; + case QTextCursor::Right: + newPosition = visualMovement ? priv->rightCursorPosition(position) + : priv->nextCursorPosition(position, QTextLayout::SkipCharacters); + break; case QTextCursor::NextWord: case QTextCursor::WordRight: newPosition = priv->nextCursorPosition(position, QTextLayout::SkipWords); @@ -2558,4 +2567,19 @@ QTextDocument *QTextCursor::document() const return 0; // document went away } +/*! + \enum Qt::CursorMoveStyle + + This enum describes the movement style available to text cursors. The options + are: + + \value LogicalMoveStyle Within a left-to-right text block, decrease cursor + position when pressing left arrow key, increase cursor position when pressing + the right arrow key. If the text block is right-to-left, the opposite behavior + applies. + \value VisualMoveStyle Pressing the left arrow key will always cause the cursor + to move left, regardless of the text's writing direction. Pressing the right + arrow key will always cause the cursor to move right. +*/ + QT_END_NAMESPACE diff --git a/src/gui/text/qtextdocument.cpp b/src/gui/text/qtextdocument.cpp index 6dbd755..0d33912 100644 --- a/src/gui/text/qtextdocument.cpp +++ b/src/gui/text/qtextdocument.cpp @@ -586,6 +586,29 @@ void QTextDocument::setDefaultTextOption(const QTextOption &option) } /*! + \since 4.8 + + The default cursor movement style is used by all QTextCursor objects + created from the document. The default is Qt::LogicalMoveStyle. +*/ +Qt::CursorMoveStyle QTextDocument::defaultCursorMoveStyle() const +{ + Q_D(const QTextDocument); + return d->defaultCursorMoveStyle; +} + +/*! + \since 4.8 + + Set the default cursor movement style. +*/ +void QTextDocument::setDefaultCursorMoveStyle(Qt::CursorMoveStyle style) +{ + Q_D(QTextDocument); + d->defaultCursorMoveStyle = style; +} + +/*! \fn void QTextDocument::markContentsDirty(int position, int length) Marks the contents specified by the given \a position and \a length @@ -2076,6 +2099,10 @@ QString QTextHtmlExporter::toHtml(const QByteArray &encoding, ExportMode mode) html += QLatin1String(" font-size:"); html += QString::number(defaultCharFormat.fontPointSize()); html += QLatin1String("pt;"); + } else if (defaultCharFormat.hasProperty(QTextFormat::FontPixelSize)) { + html += QLatin1String(" font-size:"); + html += QString::number(defaultCharFormat.intProperty(QTextFormat::FontPixelSize)); + html += QLatin1String("px;"); } html += QLatin1String(" font-weight:"); @@ -2156,6 +2183,10 @@ bool QTextHtmlExporter::emitCharFormatStyle(const QTextCharFormat &format) html += QLatin1Char(';'); attributesEmitted = true; } + } else if (format.hasProperty(QTextFormat::FontPixelSize)) { + html += QLatin1String(" font-size:"); + html += QString::number(format.intProperty(QTextFormat::FontPixelSize)); + html += QLatin1String("px;"); } if (format.hasProperty(QTextFormat::FontWeight) diff --git a/src/gui/text/qtextdocument.h b/src/gui/text/qtextdocument.h index f87ccc9..b826dc1 100644 --- a/src/gui/text/qtextdocument.h +++ b/src/gui/text/qtextdocument.h @@ -60,7 +60,6 @@ class QPainter; class QPrinter; class QAbstractTextDocumentLayout; class QPoint; -class QTextCursor; class QTextObject; class QTextFormat; class QTextFrame; @@ -70,6 +69,7 @@ class QUrl; class QVariant; class QRectF; class QTextOption; +class QTextCursor; template<typename T> class QVector; @@ -269,6 +269,9 @@ public: QTextOption defaultTextOption() const; void setDefaultTextOption(const QTextOption &option); + Qt::CursorMoveStyle defaultCursorMoveStyle() const; + void setDefaultCursorMoveStyle(Qt::CursorMoveStyle style); + Q_SIGNALS: void contentsChange(int from, int charsRemoves, int charsAdded); void contentsChanged(); diff --git a/src/gui/text/qtextdocument_p.cpp b/src/gui/text/qtextdocument_p.cpp index a997720..640f7aa 100644 --- a/src/gui/text/qtextdocument_p.cpp +++ b/src/gui/text/qtextdocument_p.cpp @@ -209,6 +209,7 @@ QTextDocumentPrivate::QTextDocumentPrivate() defaultTextOption.setTabStop(80); // same as in qtextengine.cpp defaultTextOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); + defaultCursorMoveStyle = Qt::LogicalMoveStyle; indentWidth = 40; documentMargin = 4; @@ -1382,6 +1383,20 @@ int QTextDocumentPrivate::previousCursorPosition(int position, QTextLayout::Curs return it.layout()->previousCursorPosition(position-start, mode) + start; } +int QTextDocumentPrivate::leftCursorPosition(int position) const +{ + QTextBlock it = blocksFind(position); + int start = it.position(); + return it.layout()->leftCursorPosition(position-start) + start; +} + +int QTextDocumentPrivate::rightCursorPosition(int position) const +{ + QTextBlock it = blocksFind(position); + int start = it.position(); + return it.layout()->rightCursorPosition(position-start) + start; +} + void QTextDocumentPrivate::changeObjectFormat(QTextObject *obj, int format) { beginEditBlock(); diff --git a/src/gui/text/qtextdocument_p.h b/src/gui/text/qtextdocument_p.h index b464f2e..e72d676 100644 --- a/src/gui/text/qtextdocument_p.h +++ b/src/gui/text/qtextdocument_p.h @@ -64,6 +64,7 @@ #include "private/qtextformat_p.h" #include "QtGui/qtextdocument.h" #include "QtGui/qtextobject.h" +#include "QtGui/qtextcursor.h" #include "QtCore/qmap.h" #include "QtCore/qvariant.h" #include "QtCore/qurl.h" @@ -244,6 +245,8 @@ public: int nextCursorPosition(int position, QTextLayout::CursorMode mode) const; int previousCursorPosition(int position, QTextLayout::CursorMode mode) const; + int leftCursorPosition(int position) const; + int rightCursorPosition(int position) const; void changeObjectFormat(QTextObject *group, int format); @@ -339,6 +342,7 @@ private: public: QTextOption defaultTextOption; + Qt::CursorMoveStyle defaultCursorMoveStyle; #ifndef QT_NO_CSSPARSER QCss::StyleSheet parsedDefaultStyleSheet; #endif diff --git a/src/gui/text/qtextdocumentlayout.cpp b/src/gui/text/qtextdocumentlayout.cpp index ce157be..f3dc975 100644 --- a/src/gui/text/qtextdocumentlayout.cpp +++ b/src/gui/text/qtextdocumentlayout.cpp @@ -2996,10 +2996,19 @@ void QTextDocumentLayout::resizeInlineObject(QTextInlineObject item, int posInDo QSizeF inlineSize = (pos == QTextFrameFormat::InFlow ? intrinsic : QSizeF(0, 0)); item.setWidth(inlineSize.width()); - if (f.verticalAlignment() == QTextCharFormat::AlignMiddle) { + + QFontMetrics m(f.font()); + switch (f.verticalAlignment()) + { + case QTextCharFormat::AlignMiddle: item.setDescent(inlineSize.height() / 2); item.setAscent(inlineSize.height() / 2 - 1); - } else { + break; + case QTextCharFormat::AlignBaseline: + item.setDescent(m.descent()); + item.setAscent(inlineSize.height() - m.descent() - 1); + break; + default: item.setDescent(0); item.setAscent(inlineSize.height() - 1); } @@ -3081,6 +3090,7 @@ void QTextDocumentLayoutPrivate::ensureLayouted(QFixed y) const if (currentLazyLayoutPosition == -1) return; const QSizeF oldSize = q->dynamicDocumentSize(); + Q_UNUSED(oldSize); if (checkPoints.isEmpty()) layoutStep(); diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp index 08d0eca..ff27bc6 100644 --- a/src/gui/text/qtextengine.cpp +++ b/src/gui/text/qtextengine.cpp @@ -856,6 +856,21 @@ void QTextEngine::shapeLine(const QScriptLine &line) } } +#if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC) +static bool enableHarfBuzz() +{ + static enum { Yes, No, Unknown } status = Unknown; + + if (status == Unknown) { + QByteArray v = qgetenv("QT_ENABLE_HARFBUZZ"); + bool value = !v.isEmpty() && v != "0" && v != "false"; + if (value) status = Yes; + else status = No; + } + return status == Yes; +} +#endif + void QTextEngine::shapeText(int item) const { Q_ASSERT(item < layoutData->items.size()); @@ -865,7 +880,24 @@ void QTextEngine::shapeText(int item) const return; #if defined(Q_WS_MAC) - shapeTextMac(item); +#if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC) + if (enableHarfBuzz()) { +#endif + QFontEngine *actualFontEngine = fontEngine(si, &si.ascent, &si.descent, &si.leading); + if (actualFontEngine->type() == QFontEngine::Multi) + actualFontEngine = static_cast<QFontEngineMulti *>(actualFontEngine)->engine(0); + + HB_Face face = actualFontEngine->harfbuzzFace(); + HB_Script script = (HB_Script) si.analysis.script; + if (face->supported_scripts[script]) + shapeTextWithHarfbuzz(item); + else + shapeTextMac(item); +#if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC) + } else { + shapeTextMac(item); + } +#endif #elif defined(Q_WS_WINCE) shapeTextWithCE(item); #else @@ -1242,6 +1274,10 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx); } + si.ascent = qMax(actualFontEngine->ascent(), si.ascent); + si.descent = qMax(actualFontEngine->descent(), si.descent); + si.leading = qMax(actualFontEngine->leading(), si.leading); + shaper_item.font = actualFontEngine->harfbuzzFont(); shaper_item.face = actualFontEngine->harfbuzzFace(); @@ -1304,6 +1340,7 @@ static void init(QTextEngine *e) e->ignoreBidi = false; e->cacheGlyphs = false; e->forceJustification = false; + e->visualMovement = false; e->layoutData = 0; @@ -1565,6 +1602,8 @@ bool QTextEngine::isRightToLeft() const default: break; } + if (!layoutData) + itemize(); // this places the cursor in the right position depending on the keyboard layout if (layoutData->string.isEmpty()) return QApplication::keyboardInputDirection() == Qt::RightToLeft; @@ -2737,6 +2776,182 @@ QFixed QTextEngine::leadingSpaceWidth(const QScriptLine &line) return width(line.from + pos, line.length - pos); } +QFixed QTextEngine::alignLine(const QScriptLine &line) +{ + QFixed x = 0; + justify(line); + // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned. + if (!line.justified && line.width != QFIXED_MAX) { + int align = option.alignment(); + if (align & Qt::AlignLeft) + x -= leadingSpaceWidth(line); + if (align & Qt::AlignJustify && isRightToLeft()) + align = Qt::AlignRight; + if (align & Qt::AlignRight) + x = line.width - (line.textAdvance + leadingSpaceWidth(line)); + else if (align & Qt::AlignHCenter) + x = (line.width - (line.textAdvance + leadingSpaceWidth(line)))/2; + } + return x; +} + +QFixed QTextEngine::offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos) +{ + unsigned short *logClusters = this->logClusters(si); + const QGlyphLayout &glyphs = shapedGlyphs(si); + + int offsetInCluster = 0; + for (int i = pos - 1; i >= 0; i--) { + if (logClusters[i] == glyph_pos) + offsetInCluster++; + else + break; + } + + // in the case that the offset is inside a (multi-character) glyph, + // interpolate the position. + if (offsetInCluster > 0) { + int clusterLength = 0; + for (int i = pos - offsetInCluster; i < max; i++) { + if (logClusters[i] == glyph_pos) + clusterLength++; + else + break; + } + if (clusterLength) + return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength; + } + + return 0; +} + +int QTextEngine::previousLogicalPosition(int oldPos) const +{ + const HB_CharAttributes *attrs = attributes(); + if (!attrs || oldPos < 0) + return oldPos; + + if (oldPos <= 0) + return 0; + oldPos--; + while (oldPos && !attrs[oldPos].charStop) + oldPos--; + return oldPos; +} + +int QTextEngine::nextLogicalPosition(int oldPos) const +{ + const HB_CharAttributes *attrs = attributes(); + int len = block.isValid() ? block.length() - 1 + : layoutData->string.length(); + Q_ASSERT(len <= layoutData->string.length()); + if (!attrs || oldPos < 0 || oldPos >= len) + return oldPos; + + oldPos++; + while (oldPos < len && !attrs[oldPos].charStop) + oldPos++; + return oldPos; +} + +int QTextEngine::lineNumberForTextPosition(int pos) +{ + if (!layoutData) + itemize(); + if (pos == layoutData->string.length() && lines.size()) + return lines.size() - 1; + for (int i = 0; i < lines.size(); ++i) { + const QScriptLine& line = lines[i]; + if (line.from + line.length > pos) + return i; + } + return -1; +} + +void QTextEngine::insertionPointsForLine(int lineNum, QVector<int> &insertionPoints) +{ + QTextLineItemIterator iterator(this, lineNum); + bool rtl = isRightToLeft(); + bool lastLine = lineNum >= lines.size() - 1; + + while (!iterator.atEnd()) { + iterator.next(); + const QScriptItem *si = &layoutData->items[iterator.item]; + if (si->analysis.bidiLevel % 2) { + int i = iterator.itemEnd - 1, min = iterator.itemStart; + if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd())) + i++; + for (; i >= min; i--) + insertionPoints.push_back(i); + } else { + int i = iterator.itemStart, max = iterator.itemEnd; + if (lastLine && (rtl ? iterator.atBeginning() : iterator.atEnd())) + max++; + for (; i < max; i++) + insertionPoints.push_back(i); + } + } +} + +int QTextEngine::endOfLine(int lineNum) +{ + QVector<int> insertionPoints; + insertionPointsForLine(lineNum, insertionPoints); + + if (insertionPoints.size() > 0) + return insertionPoints.last(); + return 0; +} + +int QTextEngine::beginningOfLine(int lineNum) +{ + QVector<int> insertionPoints; + insertionPointsForLine(lineNum, insertionPoints); + + if (insertionPoints.size() > 0) + return insertionPoints.first(); + return 0; +} + +int QTextEngine::positionAfterVisualMovement(int pos, QTextCursor::MoveOperation op) +{ + if (!layoutData) + itemize(); + + bool moveRight = (op == QTextCursor::Right); + bool alignRight = isRightToLeft(); + if (!layoutData->hasBidi) + return moveRight ^ alignRight ? nextLogicalPosition(pos) : previousLogicalPosition(pos); + + int lineNum = lineNumberForTextPosition(pos); + Q_ASSERT(lineNum >= 0); + + QVector<int> insertionPoints; + insertionPointsForLine(lineNum, insertionPoints); + int i, max = insertionPoints.size(); + for (i = 0; i < max; i++) + if (pos == insertionPoints[i]) { + if (moveRight) { + if (i + 1 < max) + return insertionPoints[i + 1]; + } else { + if (i > 0) + return insertionPoints[i - 1]; + } + + if (moveRight ^ alignRight) { + if (lineNum + 1 < lines.size()) + return alignRight ? endOfLine(lineNum + 1) : beginningOfLine(lineNum + 1); + } + else { + if (lineNum > 0) + return alignRight ? beginningOfLine(lineNum - 1) : endOfLine(lineNum - 1); + } + } + + return pos; +} + QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f) : QTextEngine(string, f), _layoutData(string, _memory, MemSize) @@ -2841,5 +3056,127 @@ glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const return m; } +QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int _lineNum, const QPointF &pos, + const QTextLayout::FormatRange *_selection) + : eng(_eng), + line(eng->lines[_lineNum]), + si(0), + lineNum(_lineNum), + lineEnd(line.from + line.length), + firstItem(eng->findItem(line.from)), + lastItem(eng->findItem(lineEnd - 1)), + nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0), + logicalItem(-1), + item(-1), + visualOrder(nItems), + levels(nItems), + selection(_selection) +{ + pos_x = x = QFixed::fromReal(pos.x()); + + x += line.x; + + x += eng->alignLine(line); + + for (int i = 0; i < nItems; ++i) + levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel; + QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data()); + + eng->shapeLine(line); +} + +QScriptItem &QTextLineItemIterator::next() +{ + x += itemWidth; + + ++logicalItem; + item = visualOrder[logicalItem] + firstItem; + itemLength = eng->length(item); + si = &eng->layoutData->items[item]; + if (!si->num_glyphs) + eng->shape(item); + + if (si->analysis.flags >= QScriptAnalysis::TabOrObject) { + itemWidth = si->width; + return *si; + } + + unsigned short *logClusters = eng->logClusters(si); + QGlyphLayout glyphs = eng->shapedGlyphs(si); + + itemStart = qMax(line.from, si->position); + glyphsStart = logClusters[itemStart - si->position]; + if (lineEnd < si->position + itemLength) { + itemEnd = lineEnd; + glyphsEnd = logClusters[itemEnd-si->position]; + } else { + itemEnd = si->position + itemLength; + glyphsEnd = si->num_glyphs; + } + // show soft-hyphen at line-break + if (si->position + itemLength >= lineEnd + && eng->layoutData->string.at(lineEnd - 1) == 0x00ad) + glyphs.attributes[glyphsEnd - 1].dontPrint = false; + + itemWidth = 0; + for (int g = glyphsStart; g < glyphsEnd; ++g) + itemWidth += glyphs.effectiveAdvance(g); + + return *si; +} + +bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const +{ + *selectionX = *selectionWidth = 0; + + if (!selection) + return false; + + if (si->analysis.flags >= QScriptAnalysis::TabOrObject) { + if (si->position >= selection->start + selection->length + || si->position + itemLength <= selection->start) + return false; + + *selectionX = x; + *selectionWidth = itemWidth; + } else { + unsigned short *logClusters = eng->logClusters(si); + QGlyphLayout glyphs = eng->shapedGlyphs(si); + + int from = qMax(itemStart, selection->start) - si->position; + int to = qMin(itemEnd, selection->start + selection->length) - si->position; + if (from >= to) + return false; + + int start_glyph = logClusters[from]; + int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to]; + QFixed soff; + QFixed swidth; + if (si->analysis.bidiLevel %2) { + for (int g = glyphsEnd - 1; g >= end_glyph; --g) + soff += glyphs.effectiveAdvance(g); + for (int g = end_glyph - 1; g >= start_glyph; --g) + swidth += glyphs.effectiveAdvance(g); + } else { + for (int g = glyphsStart; g < start_glyph; ++g) + soff += glyphs.effectiveAdvance(g); + for (int g = start_glyph; g < end_glyph; ++g) + swidth += glyphs.effectiveAdvance(g); + } + + // If the starting character is in the middle of a ligature, + // selection should only contain the right part of that ligature + // glyph, so we need to get the width of the left part here and + // add it to *selectionX + QFixed leftOffsetInLigature = eng->offsetInLigature(si, from, to, start_glyph); + *selectionX = x + soff + leftOffsetInLigature; + *selectionWidth = swidth - leftOffsetInLigature; + // If the ending character is also part of a ligature, swidth does + // not contain that part yet, we also need to find out the width of + // that left part + *selectionWidth += eng->offsetInLigature(si, to, eng->length(item), end_glyph); + } + return true; +} QT_END_NAMESPACE diff --git a/src/gui/text/qtextengine_mac.cpp b/src/gui/text/qtextengine_mac.cpp index 97e8c5b..2c6e579 100644 --- a/src/gui/text/qtextengine_mac.cpp +++ b/src/gui/text/qtextengine_mac.cpp @@ -605,11 +605,11 @@ void QTextEngine::shapeTextMac(int item) const unsigned short *log_clusters = logClusters(&si); bool stringToCMapFailed = false; - if (!fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, attributes())) { + if (!fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, attributes(), &si)) { ensureSpace(num_glyphs); g = availableGlyphs(&si); stringToCMapFailed = !fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, - attributes()); + attributes(), &si); } if (!stringToCMapFailed) { diff --git a/src/gui/text/qtextengine_p.h b/src/gui/text/qtextengine_p.h index 366c5c3..e06ca1c 100644 --- a/src/gui/text/qtextengine_p.h +++ b/src/gui/text/qtextengine_p.h @@ -64,6 +64,7 @@ #include "QtGui/qpaintengine.h" #include "QtGui/qtextobject.h" #include "QtGui/qtextoption.h" +#include "QtGui/qtextcursor.h" #include "QtCore/qset.h" #include "QtCore/qdebug.h" #ifndef QT_BUILD_COMPAT_LIB @@ -471,6 +472,7 @@ public: void shape(int item) const; void justify(const QScriptLine &si); + QFixed alignLine(const QScriptLine &line); QFixed width(int charFrom, int numChars) const; glyph_metrics_t boundingBox(int from, int len) const; @@ -586,12 +588,18 @@ public: uint cacheGlyphs : 1; uint stackEngine : 1; uint forceJustification : 1; + uint visualMovement : 1; int *underlinePositions; mutable LayoutData *layoutData; inline bool hasFormats() const { return (block.docHandle() || specialData); } + inline bool visualCursorMovement() const + { + return (visualMovement || + (block.docHandle() ? block.docHandle()->defaultCursorMoveStyle == Qt::VisualMoveStyle : false)); + } struct SpecialData { int preeditPosition; @@ -611,6 +619,13 @@ public: void shapeLine(const QScriptLine &line); QFixed leadingSpaceWidth(const QScriptLine &line); + QFixed offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos); + int previousLogicalPosition(int oldPos) const; + int nextLogicalPosition(int oldPos) const; + int lineNumberForTextPosition(int pos); + int positionAfterVisualMovement(int oldPos, QTextCursor::MoveOperation op); + void insertionPointsForLine(int lineNum, QVector<int> &insertionPoints); + private: void setBoundary(int strPos) const; void addRequiredBoundaries() const; @@ -625,6 +640,8 @@ private: void splitItem(int item, int pos) const; void resolveAdditionalFormats() const; + int endOfLine(int lineNum); + int beginningOfLine(int lineNum); }; class QStackTextEngine : public QTextEngine { @@ -635,6 +652,49 @@ public: void *_memory[MemSize]; }; +struct QTextLineItemIterator +{ + QTextLineItemIterator(QTextEngine *eng, int lineNum, const QPointF &pos = QPointF(), + const QTextLayout::FormatRange *_selection = 0); + + inline bool atEnd() const { return logicalItem >= nItems - 1; } + inline bool atBeginning() const { return logicalItem <= 0; } + QScriptItem &next(); + + bool getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const; + inline bool isOutsideSelection() const { + QFixed tmp1, tmp2; + return !getSelectionBounds(&tmp1, &tmp2); + } + + QTextEngine *eng; + + QFixed x; + QFixed pos_x; + const QScriptLine &line; + QScriptItem *si; + + int lineNum; + int lineEnd; + int firstItem; + int lastItem; + int nItems; + int logicalItem; + int item; + int itemLength; + + int glyphsStart; + int glyphsEnd; + int itemStart; + int itemEnd; + + QFixed itemWidth; + + QVarLengthArray<int> visualOrder; + QVarLengthArray<uchar> levels; + + const QTextLayout::FormatRange *selection; +}; Q_DECLARE_OPERATORS_FOR_FLAGS(QTextEngine::ShaperFlags) diff --git a/src/gui/text/qtextformat.h b/src/gui/text/qtextformat.h index ff28eaa..4f4752a 100644 --- a/src/gui/text/qtextformat.h +++ b/src/gui/text/qtextformat.h @@ -378,7 +378,8 @@ public: AlignSubScript, AlignMiddle, AlignTop, - AlignBottom + AlignBottom, + AlignBaseline }; enum UnderlineStyle { // keep in sync with Qt::PenStyle! NoUnderline, diff --git a/src/gui/text/qtextlayout.cpp b/src/gui/text/qtextlayout.cpp index 93f71d3..07aeb72 100644 --- a/src/gui/text/qtextlayout.cpp +++ b/src/gui/text/qtextlayout.cpp @@ -52,8 +52,8 @@ #include "qtextformat_p.h" #include "qstyleoption.h" #include "qpainterpath.h" -#include "qglyphs.h" -#include "qglyphs_p.h" +#include "qglyphrun.h" +#include "qglyphrun_p.h" #include "qrawfont.h" #include "qrawfont_p.h" #include <limits.h> @@ -72,23 +72,6 @@ QT_BEGIN_NAMESPACE #define SuppressText 0x5012 #define SuppressBackground 0x513 -static QFixed alignLine(QTextEngine *eng, const QScriptLine &line) -{ - QFixed x = 0; - eng->justify(line); - // if width is QFIXED_MAX that means we used setNumColumns() and that implicitly makes this line left aligned. - if (!line.justified && line.width != QFIXED_MAX) { - int align = eng->option.alignment(); - if (align & Qt::AlignJustify && eng->isRightToLeft()) - align = Qt::AlignRight; - if (align & Qt::AlignRight) - x = line.width - (line.textAdvance + eng->leadingSpaceWidth(line)); - else if (align & Qt::AlignHCenter) - x = (line.width - line.textAdvance)/2; - } - return x; -} - /*! \class QTextLayout::FormatRange \reentrant @@ -596,6 +579,30 @@ bool QTextLayout::cacheEnabled() const } /*! + Set the cursor movement style. If the QTextLayout is backed by + a document, you can ignore this and use the option in QTextDocument, + this option is for widgets like QLineEdit or custom widgets without + a QTextDocument. Default value is Qt::LogicalMoveStyle. + + \sa setCursorMoveStyle() +*/ +void QTextLayout::setCursorMoveStyle(Qt::CursorMoveStyle style) +{ + d->visualMovement = style == Qt::VisualMoveStyle ? true : false; +} + +/*! + The cursor movement style of this QTextLayout. The default is + Qt::LogicalMoveStyle. + + \sa setCursorMoveStyle() +*/ +Qt::CursorMoveStyle QTextLayout::cursorMoveStyle() const +{ + return d->visualMovement ? Qt::VisualMoveStyle : Qt::LogicalMoveStyle; +} + +/*! Begins the layout process. \sa endLayout() @@ -718,6 +725,34 @@ int QTextLayout::previousCursorPosition(int oldPos, CursorMode mode) const } /*! + Returns the cursor position to the right of \a oldPos, next to it. + It's dependent on the visual position of characters, after bi-directional + reordering. + + \sa leftCursorPosition(), nextCursorPosition() +*/ +int QTextLayout::rightCursorPosition(int oldPos) const +{ + int newPos = d->positionAfterVisualMovement(oldPos, QTextCursor::Right); +// qDebug("%d -> %d", oldPos, newPos); + return newPos; +} + +/*! + Returns the cursor position to the left of \a oldPos, next to it. + It's dependent on the visual position of characters, after bi-directional + reordering. + + \sa rightCursorPosition(), previousCursorPosition() +*/ +int QTextLayout::leftCursorPosition(int oldPos) const +{ + int newPos = d->positionAfterVisualMovement(oldPos, QTextCursor::Left); +// qDebug("%d -> %d", oldPos, newPos); + return newPos; +} + +/*!/ Returns true if position \a pos is a valid cursor position. In a Unicode context some positions in the text are not valid @@ -815,16 +850,8 @@ QTextLine QTextLayout::lineAt(int i) const */ QTextLine QTextLayout::lineForTextPosition(int pos) const { - for (int i = 0; i < d->lines.size(); ++i) { - const QScriptLine& line = d->lines[i]; - if (line.from + (int)line.length > pos) - return QTextLine(i, d); - } - if (!d->layoutData) - d->itemize(); - if (pos == d->layoutData->string.length() && d->lines.size()) - return QTextLine(d->lines.size()-1, d); - return QTextLine(); + int lineNum = d->lineNumberForTextPosition(pos); + return lineNum >= 0 ? lineAt(lineNum) : QTextLine(); } /*! @@ -919,201 +946,6 @@ void QTextLayout::setFlags(int flags) } } -struct QTextLineItemIterator -{ - QTextLineItemIterator(QTextEngine *eng, int lineNum, const QPointF &pos = QPointF(), - const QTextLayout::FormatRange *_selection = 0); - - inline bool atEnd() const { return logicalItem >= nItems - 1; } - QScriptItem &next(); - - bool getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const; - inline bool isOutsideSelection() const { - QFixed tmp1, tmp2; - return !getSelectionBounds(&tmp1, &tmp2); - } - - QTextEngine *eng; - - QFixed x; - QFixed pos_x; - const QScriptLine &line; - QScriptItem *si; - - int lineEnd; - int firstItem; - int lastItem; - int nItems; - int logicalItem; - int item; - int itemLength; - - int glyphsStart; - int glyphsEnd; - int itemStart; - int itemEnd; - - QFixed itemWidth; - - QVarLengthArray<int> visualOrder; - QVarLengthArray<uchar> levels; - - const QTextLayout::FormatRange *selection; -}; - -QTextLineItemIterator::QTextLineItemIterator(QTextEngine *_eng, int lineNum, const QPointF &pos, - const QTextLayout::FormatRange *_selection) - : eng(_eng), - line(eng->lines[lineNum]), - si(0), - lineEnd(line.from + line.length), - firstItem(eng->findItem(line.from)), - lastItem(eng->findItem(lineEnd - 1)), - nItems((firstItem >= 0 && lastItem >= firstItem)? (lastItem-firstItem+1) : 0), - logicalItem(-1), - item(-1), - visualOrder(nItems), - levels(nItems), - selection(_selection) -{ - pos_x = x = QFixed::fromReal(pos.x()); - - x += line.x; - - x += alignLine(eng, line); - - for (int i = 0; i < nItems; ++i) - levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel; - QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data()); - - eng->shapeLine(line); -} - -QScriptItem &QTextLineItemIterator::next() -{ - x += itemWidth; - - ++logicalItem; - item = visualOrder[logicalItem] + firstItem; - itemLength = eng->length(item); - si = &eng->layoutData->items[item]; - if (!si->num_glyphs) - eng->shape(item); - - if (si->analysis.flags >= QScriptAnalysis::TabOrObject) { - itemWidth = si->width; - return *si; - } - - unsigned short *logClusters = eng->logClusters(si); - QGlyphLayout glyphs = eng->shapedGlyphs(si); - - itemStart = qMax(line.from, si->position); - glyphsStart = logClusters[itemStart - si->position]; - if (lineEnd < si->position + itemLength) { - itemEnd = lineEnd; - glyphsEnd = logClusters[itemEnd-si->position]; - } else { - itemEnd = si->position + itemLength; - glyphsEnd = si->num_glyphs; - } - // show soft-hyphen at line-break - if (si->position + itemLength >= lineEnd - && eng->layoutData->string.at(lineEnd - 1) == 0x00ad) - glyphs.attributes[glyphsEnd - 1].dontPrint = false; - - itemWidth = 0; - for (int g = glyphsStart; g < glyphsEnd; ++g) - itemWidth += glyphs.effectiveAdvance(g); - - return *si; -} - -static QFixed offsetInLigature(const unsigned short *logClusters, - const QGlyphLayout &glyphs, - int pos, int max, int glyph_pos) -{ - int offsetInCluster = 0; - for (int i = pos - 1; i >= 0; i--) { - if (logClusters[i] == glyph_pos) - offsetInCluster++; - else - break; - } - - // in the case that the offset is inside a (multi-character) glyph, - // interpolate the position. - if (offsetInCluster > 0) { - int clusterLength = 0; - for (int i = pos - offsetInCluster; i < max; i++) { - if (logClusters[i] == glyph_pos) - clusterLength++; - else - break; - } - if (clusterLength) - return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength; - } - - return 0; -} - -bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const -{ - *selectionX = *selectionWidth = 0; - - if (!selection) - return false; - - if (si->analysis.flags >= QScriptAnalysis::TabOrObject) { - if (si->position >= selection->start + selection->length - || si->position + itemLength <= selection->start) - return false; - - *selectionX = x; - *selectionWidth = itemWidth; - } else { - unsigned short *logClusters = eng->logClusters(si); - QGlyphLayout glyphs = eng->shapedGlyphs(si); - - int from = qMax(itemStart, selection->start) - si->position; - int to = qMin(itemEnd, selection->start + selection->length) - si->position; - if (from >= to) - return false; - - int start_glyph = logClusters[from]; - int end_glyph = (to == eng->length(item)) ? si->num_glyphs : logClusters[to]; - QFixed soff; - QFixed swidth; - if (si->analysis.bidiLevel %2) { - for (int g = glyphsEnd - 1; g >= end_glyph; --g) - soff += glyphs.effectiveAdvance(g); - for (int g = end_glyph - 1; g >= start_glyph; --g) - swidth += glyphs.effectiveAdvance(g); - } else { - for (int g = glyphsStart; g < start_glyph; ++g) - soff += glyphs.effectiveAdvance(g); - for (int g = start_glyph; g < end_glyph; ++g) - swidth += glyphs.effectiveAdvance(g); - } - - // If the starting character is in the middle of a ligature, - // selection should only contain the right part of that ligature - // glyph, so we need to get the width of the left part here and - // add it to *selectionX - QFixed leftOffsetInLigature = offsetInLigature(logClusters, glyphs, from, - to, start_glyph); - *selectionX = x + soff + leftOffsetInLigature; - *selectionWidth = swidth - leftOffsetInLigature; - // If the ending character is also part of a ligature, swidth does - // not contain that part yet, we also need to find out the width of - // that left part - *selectionWidth += offsetInLigature(logClusters, glyphs, to, - eng->length(item), end_glyph); - } - return true; -} - static void addSelectedRegionsToPath(QTextEngine *eng, int lineNumber, const QPointF &pos, QTextLayout::FormatRange *selection, QPainterPath *region, QRectF boundingRect) { @@ -1162,12 +994,12 @@ static inline QRectF clipIfValid(const QRectF &rect, const QRectF &clip) \since 4.8 - \sa draw(), QPainter::drawGlyphs() + \sa draw(), QPainter::drawGlyphRun() */ #if !defined(QT_NO_RAWFONT) -QList<QGlyphs> QTextLayout::glyphs() const +QList<QGlyphRun> QTextLayout::glyphRuns() const { - QList<QGlyphs> glyphs; + QList<QGlyphRun> glyphs; for (int i=0; i<d->lines.size(); ++i) glyphs += QTextLine(i, d).glyphs(-1, -1); @@ -1228,6 +1060,7 @@ void QTextLayout::draw(QPainter *p, const QPointF &pos, const QVector<FormatRang QRectF lineRect(tl.naturalTextRect()); lineRect.translate(position); + lineRect.adjust(0, 0, d->leadingSpaceWidth(sl).toReal(), 0); bool isLastLineInBlock = (line == d->lines.size()-1); int sl_length = sl.length + (isLastLineInBlock? 1 : 0); // the infamous newline @@ -1378,22 +1211,11 @@ void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition d->itemize(); QPointF position = pos + d->position; - QFixed pos_x = QFixed::fromReal(position.x()); - QFixed pos_y = QFixed::fromReal(position.y()); cursorPosition = qBound(0, cursorPosition, d->layoutData->string.length()); - int line = 0; - if (cursorPosition == d->layoutData->string.length()) { - line = d->lines.size() - 1; - } else { - // ### binary search - for (line = 0; line < d->lines.size(); line++) { - const QScriptLine &sl = d->lines[line]; - if (sl.from <= cursorPosition && sl.from + (int)sl.length > cursorPosition) - break; - } - } - + int line = d->lineNumberForTextPosition(cursorPosition); + if (line < 0) + line = 0; if (line >= d->lines.size()) return; @@ -1402,7 +1224,15 @@ void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition qreal x = position.x() + l.cursorToX(cursorPosition); - int itm = d->findItem(cursorPosition - 1); + int itm; + + if (d->visualCursorMovement()) { + if (cursorPosition == sl.from + sl.length) + cursorPosition--; + itm = d->findItem(cursorPosition); + } else + itm = d->findItem(cursorPosition - 1); + QFixed base = sl.base(); QFixed descent = sl.descent; bool rightToLeft = d->isRightToLeft(); @@ -1512,7 +1342,7 @@ QRectF QTextLine::rect() const QRectF QTextLine::naturalTextRect() const { const QScriptLine& sl = eng->lines[i]; - QFixed x = sl.x + alignLine(eng, sl); + QFixed x = sl.x + eng->alignLine(sl); QFixed width = sl.textWidth; if (sl.justified) @@ -2263,15 +2093,15 @@ namespace { \since 4.8 - \sa QTextLayout::glyphs() + \sa QTextLayout::glyphRuns() */ #if !defined(QT_NO_RAWFONT) -QList<QGlyphs> QTextLine::glyphs(int from, int length) const +QList<QGlyphRun> QTextLine::glyphs(int from, int length) const { const QScriptLine &line = eng->lines[i]; if (line.length == 0) - return QList<QGlyphs>(); + return QList<QGlyphRun>(); QHash<QFontEngine *, GlyphInfo> glyphLayoutHash; @@ -2317,6 +2147,9 @@ QList<QGlyphs> QTextLine::glyphs(int from, int length) const QGlyphLayout subLayout = glyphLayout.mid(start, end - start); glyphLayoutHash.insertMulti(multiFontEngine->engine(which), GlyphInfo(subLayout, pos, flags)); + for (int i = 0; i < subLayout.numGlyphs; i++) + pos += QPointF(subLayout.advances_x[i].toReal(), + subLayout.advances_y[i].toReal()); start = end; which = e; @@ -2333,7 +2166,7 @@ QList<QGlyphs> QTextLine::glyphs(int from, int length) const } } - QHash<QPair<QFontEngine *, int>, QGlyphs> glyphsHash; + QHash<QPair<QFontEngine *, int>, QGlyphRun> glyphsHash; QList<QFontEngine *> keys = glyphLayoutHash.uniqueKeys(); for (int i=0; i<keys.size(); ++i) { @@ -2390,14 +2223,14 @@ QList<QGlyphs> QTextLine::glyphs(int from, int length) const positions.append(positionsArray.at(i).toPointF() + pos); } - QGlyphs glyphIndexes; + QGlyphRun glyphIndexes; glyphIndexes.setGlyphIndexes(glyphs); glyphIndexes.setPositions(positions); glyphIndexes.setOverline(flags.testFlag(QTextItem::Overline)); glyphIndexes.setUnderline(flags.testFlag(QTextItem::Underline)); glyphIndexes.setStrikeOut(flags.testFlag(QTextItem::StrikeOut)); - glyphIndexes.setFont(font); + glyphIndexes.setRawFont(font); QPair<QFontEngine *, int> key(fontEngine, int(flags)); if (!glyphsHash.contains(key)) @@ -2632,9 +2465,10 @@ qreal QTextLine::cursorToX(int *cursorPos, Edge edge) const eng->itemize(); const QScriptLine &line = eng->lines[i]; + bool lastLine = i >= eng->lines.size() - 1; QFixed x = line.x; - x += alignLine(eng, line); + x += eng->alignLine(line); if (!i && !eng->layoutData->items.size()) { *cursorPos = 0; @@ -2720,21 +2554,29 @@ qreal QTextLine::cursorToX(int *cursorPos, Edge edge) const logClusters = eng->logClusters(si); glyphs = eng->shapedGlyphs(si); if (si->analysis.flags >= QScriptAnalysis::TabOrObject) { - if(pos == l) + if (pos == (reverse ? 0 : l)) x += si->width; } else { + bool rtl = eng->isRightToLeft(); + bool visual = eng->visualCursorMovement(); if (reverse) { int end = qMin(lineEnd, si->position + l) - si->position; int glyph_end = end == l ? si->num_glyphs : logClusters[end]; - for (int i = glyph_end - 1; i >= glyph_pos; i--) + int glyph_start = glyph_pos; + if (visual && !rtl && !(lastLine && itm == (visualOrder[nItems - 1] + firstItem))) + glyph_start++; + for (int i = glyph_end - 1; i >= glyph_start; i--) x += glyphs.effectiveAdvance(i); } else { int start = qMax(line.from - si->position, 0); int glyph_start = logClusters[start]; - for (int i = glyph_start; i < glyph_pos; i++) + int glyph_end = glyph_pos; + if (!visual || !rtl || (lastLine && itm == visualOrder[0] + firstItem)) + glyph_end--; + for (int i = glyph_start; i <= glyph_end; i++) x += glyphs.effectiveAdvance(i); } - x += offsetInLigature(logClusters, glyphs, pos, line.length, glyph_pos); + x += eng->offsetInLigature(si, pos, line.length, glyph_pos); } *cursorPos = pos + si->position; @@ -2753,6 +2595,8 @@ int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const { QFixed x = QFixed::fromReal(_x); const QScriptLine &line = eng->lines[i]; + bool lastLine = i >= eng->lines.size() - 1; + int lineNum = i; if (!eng->layoutData) eng->itemize(); @@ -2770,7 +2614,7 @@ int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const return 0; x -= line.x; - x -= alignLine(eng, line); + x -= eng->alignLine(line); // qDebug("xToCursor: x=%f, cpos=%d", x.toReal(), cpos); QVarLengthArray<int> visualOrder(nItems); @@ -2779,6 +2623,7 @@ int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const levels[i] = eng->layoutData->items[i+firstItem].analysis.bidiLevel; QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data()); + bool visual = eng->visualCursorMovement(); if (x <= 0) { // left of first item int item = visualOrder[0]+firstItem; @@ -2795,8 +2640,13 @@ int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const || (line.justified && x < line.width)) { // has to be in one of the runs QFixed pos; + bool rtl = eng->isRightToLeft(); eng->shapeLine(line); + QVector<int> insertionPoints; + if (visual && rtl) + eng->insertionPointsForLine(lineNum, insertionPoints); + int nchars = 0; for (int i = 0; i < nItems; ++i) { int item = visualOrder[i]+firstItem; QScriptItem &si = eng->layoutData->items[item]; @@ -2826,6 +2676,7 @@ int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const if (pos + item_width < x) { pos += item_width; + nchars += end; continue; } // qDebug(" inside run"); @@ -2870,27 +2721,60 @@ int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const } else { QFixed dist = INT_MAX/256; if (si.analysis.bidiLevel % 2) { - pos += item_width; - while (gs <= ge) { - if (glyphs.attributes[gs].clusterStart && qAbs(x-pos) < dist) { - glyph_pos = gs; - dist = qAbs(x-pos); + if (!visual || rtl || (lastLine && i == nItems - 1)) { + pos += item_width; + while (gs <= ge) { + if (glyphs.attributes[gs].clusterStart && qAbs(x-pos) < dist) { + glyph_pos = gs; + dist = qAbs(x-pos); + } + pos -= glyphs.effectiveAdvance(gs); + ++gs; + } + } else { + while (ge >= gs) { + if (glyphs.attributes[ge].clusterStart && qAbs(x-pos) < dist) { + glyph_pos = ge; + dist = qAbs(x-pos); + } + pos += glyphs.effectiveAdvance(ge); + --ge; } - pos -= glyphs.effectiveAdvance(gs); - ++gs; } } else { - while (gs <= ge) { - if (glyphs.attributes[gs].clusterStart && qAbs(x-pos) < dist) { - glyph_pos = gs; - dist = qAbs(x-pos); + if (!visual || !rtl || (lastLine && i == 0)) { + while (gs <= ge) { + if (glyphs.attributes[gs].clusterStart && qAbs(x-pos) < dist) { + glyph_pos = gs; + dist = qAbs(x-pos); + } + pos += glyphs.effectiveAdvance(gs); + ++gs; } - pos += glyphs.effectiveAdvance(gs); - ++gs; + } else { + QFixed oldPos = pos; + while (gs <= ge) { + pos += glyphs.effectiveAdvance(gs); + if (glyphs.attributes[gs].clusterStart && qAbs(x-pos) < dist) { + glyph_pos = gs; + dist = qAbs(x-pos); + } + ++gs; + } + pos = oldPos; } } - if (qAbs(x-pos) < dist) + if (qAbs(x-pos) < dist) { + if (visual) { + if (!rtl && i < nItems - 1) { + nchars += end; + continue; + } + if (rtl && nchars > 0) + return insertionPoints[lastLine ? nchars : nchars - 1]; + } return si.position + end; + } } Q_ASSERT(glyph_pos != -1); int j; diff --git a/src/gui/text/qtextlayout.h b/src/gui/text/qtextlayout.h index 9dd8ebd..89fbfb2 100644 --- a/src/gui/text/qtextlayout.h +++ b/src/gui/text/qtextlayout.h @@ -49,7 +49,8 @@ #include <QtCore/qobject.h> #include <QtGui/qevent.h> #include <QtGui/qtextformat.h> -#include <QtGui/qglyphs.h> +#include <QtGui/qglyphrun.h> +#include <QtGui/qtextcursor.h> QT_BEGIN_HEADER @@ -136,6 +137,9 @@ public: void setCacheEnabled(bool enable); bool cacheEnabled() const; + void setCursorMoveStyle(Qt::CursorMoveStyle style); + Qt::CursorMoveStyle cursorMoveStyle() const; + void beginLayout(); void endLayout(); void clearLayout(); @@ -153,6 +157,8 @@ public: bool isValidCursorPosition(int pos) const; int nextCursorPosition(int oldPos, CursorMode mode = SkipCharacters) const; int previousCursorPosition(int oldPos, CursorMode mode = SkipCharacters) const; + int leftCursorPosition(int oldPos) const; + int rightCursorPosition(int oldPos) const; void draw(QPainter *p, const QPointF &pos, const QVector<FormatRange> &selections = QVector<FormatRange>(), const QRectF &clip = QRectF()) const; @@ -168,7 +174,7 @@ public: qreal maximumWidth() const; #if !defined(QT_NO_RAWFONT) - QList<QGlyphs> glyphs() const; + QList<QGlyphRun> glyphRuns() const; #endif QTextEngine *engine() const { return d; } @@ -243,7 +249,7 @@ private: void layout_helper(int numGlyphs); #if !defined(QT_NO_RAWFONT) - QList<QGlyphs> glyphs(int from, int length) const; + QList<QGlyphRun> glyphs(int from, int length) const; #endif friend class QTextLayout; diff --git a/src/gui/text/qtextobject.cpp b/src/gui/text/qtextobject.cpp index 5c1c8b9..b7e05d2 100644 --- a/src/gui/text/qtextobject.cpp +++ b/src/gui/text/qtextobject.cpp @@ -891,11 +891,6 @@ QTextBlockUserData::~QTextBlockUserData() Returns true if this text block is valid; otherwise returns false. */ -bool QTextBlock::isValid() const -{ - return p != 0 && p->blockMap().isValid(n); -} - /*! \fn QTextBlock &QTextBlock::operator=(const QTextBlock &other) @@ -1493,7 +1488,7 @@ QTextBlock::iterator QTextBlock::end() const */ QTextBlock QTextBlock::next() const { - if (!isValid()) + if (!isValid() || !p->blockMap().isValid(n)) return QTextBlock(); return QTextBlock(p, p->blockMap().next(n)); @@ -1664,25 +1659,25 @@ QTextBlock::iterator &QTextBlock::iterator::operator--() Returns the glyphs of this text fragment. The positions of the glyphs are relative to the position of the QTextBlock's layout. - \sa QGlyphs, QTextBlock::layout(), QTextLayout::position(), QPainter::drawGlyphs() + \sa QGlyphRun, QTextBlock::layout(), QTextLayout::position(), QPainter::drawGlyphRun() */ #if !defined(QT_NO_RAWFONT) -QList<QGlyphs> QTextFragment::glyphs() const +QList<QGlyphRun> QTextFragment::glyphRuns() const { if (!p || !n) - return QList<QGlyphs>(); + return QList<QGlyphRun>(); int pos = position(); int len = length(); if (len == 0) - return QList<QGlyphs>(); + return QList<QGlyphRun>(); int blockNode = p->blockMap().findNode(pos); const QTextBlockData *blockData = p->blockMap().fragment(blockNode); QTextLayout *layout = blockData->layout; - QList<QGlyphs> ret; + QList<QGlyphRun> ret; for (int i=0; i<layout->lineCount(); ++i) { QTextLine textLine = layout->lineAt(i); ret += textLine.glyphs(pos, len); diff --git a/src/gui/text/qtextobject.h b/src/gui/text/qtextobject.h index ad8e657..a443e79 100644 --- a/src/gui/text/qtextobject.h +++ b/src/gui/text/qtextobject.h @@ -44,7 +44,7 @@ #include <QtCore/qobject.h> #include <QtGui/qtextformat.h> -#include <QtGui/qglyphs.h> +#include <QtGui/qglyphrun.h> QT_BEGIN_HEADER @@ -205,7 +205,7 @@ public: inline QTextBlock(const QTextBlock &o) : p(o.p), n(o.n) {} inline QTextBlock &operator=(const QTextBlock &o) { p = o.p; n = o.n; return *this; } - bool isValid() const; + inline bool isValid() const { return p != 0 && n != 0; } inline bool operator==(const QTextBlock &o) const { return p == o.p && n == o.n; } inline bool operator!=(const QTextBlock &o) const { return p != o.p || n != o.n; } @@ -317,7 +317,7 @@ public: QString text() const; #if !defined(QT_NO_RAWFONT) - QList<QGlyphs> glyphs() const; + QList<QGlyphRun> glyphRuns() const; #endif private: diff --git a/src/gui/text/text.pri b/src/gui/text/text.pri index df9398c..b6cdc52 100644 --- a/src/gui/text/text.pri +++ b/src/gui/text/text.pri @@ -40,10 +40,10 @@ HEADERS += \ text/qtextodfwriter_p.h \ text/qstatictext_p.h \ text/qstatictext.h \ - text/qglyphs.h \ - text/qglyphs_p.h \ text/qrawfont.h \ - text/qrawfont_p.h + text/qrawfont_p.h \ + text/qglyphrun.h \ + text/qglyphrun_p.h SOURCES += \ text/qfont.cpp \ @@ -74,8 +74,8 @@ SOURCES += \ text/qzip.cpp \ text/qtextodfwriter.cpp \ text/qstatictext.cpp \ - text/qglyphs.cpp \ - text/qrawfont.cpp + text/qrawfont.cpp \ + text/qglyphrun.cpp win32 { SOURCES += \ @@ -114,6 +114,9 @@ unix:x11 { OBJECTIVE_SOURCES += \ text/qfontengine_coretext.mm \ text/qfontengine_mac.mm + contains(QT_CONFIG, harfbuzz) { + DEFINES += QT_ENABLE_HARFBUZZ_FOR_MAC + } } embedded { @@ -136,7 +139,8 @@ qpa { SOURCES += \ text/qfont_qpa.cpp \ text/qfontengine_qpa.cpp \ - text/qplatformfontdatabase_qpa.cpp + text/qplatformfontdatabase_qpa.cpp \ + text/qrawfont_qpa.cpp HEADERS += \ text/qplatformfontdatabase_qpa.h diff --git a/src/gui/util/qflickgesture.cpp b/src/gui/util/qflickgesture.cpp deleted file mode 100644 index fdd2a95..0000000 --- a/src/gui/util/qflickgesture.cpp +++ /dev/null @@ -1,715 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgesture.h" -#include "qapplication.h" -#include "qevent.h" -#include "qwidget.h" -#include "qgraphicsitem.h" -#include "qgraphicsscene.h" -#include "qgraphicssceneevent.h" -#include "qgraphicsview.h" -#include "qscroller.h" -#include "private/qevent_p.h" -#include "private/qflickgesture_p.h" -#include "qdebug.h" - -#ifndef QT_NO_GESTURES - -QT_BEGIN_NAMESPACE - -//#define QFLICKGESTURE_DEBUG - -#ifdef QFLICKGESTURE_DEBUG -# define qFGDebug qDebug -#else -# define qFGDebug while (false) qDebug -#endif - -extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); - -static QMouseEvent *copyMouseEvent(QEvent *e) -{ - switch (e->type()) { - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseMove: { - QMouseEvent *me = static_cast<QMouseEvent *>(e); - return new QMouseEvent(me->type(), QPoint(0, 0), me->globalPos(), me->button(), me->buttons(), me->modifiers()); - } -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMousePress: - case QEvent::GraphicsSceneMouseRelease: - case QEvent::GraphicsSceneMouseMove: { - QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(e); -#if 1 - QEvent::Type met = me->type() == QEvent::GraphicsSceneMousePress ? QEvent::MouseButtonPress : - (me->type() == QEvent::GraphicsSceneMouseRelease ? QEvent::MouseButtonRelease : QEvent::MouseMove); - return new QMouseEvent(met, QPoint(0, 0), me->screenPos(), me->button(), me->buttons(), me->modifiers()); -#else - QGraphicsSceneMouseEvent *copy = new QGraphicsSceneMouseEvent(me->type()); - copy->setPos(me->pos()); - copy->setScenePos(me->scenePos()); - copy->setScreenPos(me->screenPos()); - for (int i = 0x1; i <= 0x10; i <<= 1) { - Qt::MouseButton button = Qt::MouseButton(i); - copy->setButtonDownPos(button, me->buttonDownPos(button)); - copy->setButtonDownScenePos(button, me->buttonDownScenePos(button)); - copy->setButtonDownScreenPos(button, me->buttonDownScreenPos(button)); - } - copy->setLastPos(me->lastPos()); - copy->setLastScenePos(me->lastScenePos()); - copy->setLastScreenPos(me->lastScreenPos()); - copy->setButtons(me->buttons()); - copy->setButton(me->button()); - copy->setModifiers(me->modifiers()); - return copy; -#endif - } -#endif // QT_NO_GRAPHICSVIEW - default: - return 0; - } -} - -class PressDelayHandler : public QObject -{ -private: - PressDelayHandler(QObject *parent = 0) - : QObject(parent) - , pressDelayTimer(0) - , sendingEvent(false) - , mouseButton(Qt::NoButton) - , mouseTarget(0) - { } - - static PressDelayHandler *inst; - -public: - enum { - UngrabMouseBefore = 1, - RegrabMouseAfterwards = 2 - }; - - static PressDelayHandler *instance() - { - static PressDelayHandler *inst = 0; - if (!inst) - inst = new PressDelayHandler(QCoreApplication::instance()); - return inst; - } - - bool shouldEventBeIgnored(QEvent *) const - { - return sendingEvent; - } - - bool isDelaying() const - { - return !pressDelayEvent.isNull(); - } - - void pressed(QEvent *e, int delay) - { - if (!pressDelayEvent) { - pressDelayEvent.reset(copyMouseEvent(e)); - pressDelayTimer = startTimer(delay); - mouseTarget = QApplication::widgetAt(pressDelayEvent->globalPos()); - mouseButton = pressDelayEvent->button(); - qFGDebug() << "QFG: consuming/delaying mouse press"; - } else { - qFGDebug() << "QFG: NOT consuming/delaying mouse press"; - } - e->setAccepted(true); - } - - bool released(QEvent *e, bool scrollerWasActive, bool scrollerIsActive) - { - // consume this event if the scroller was or is active - bool result = scrollerWasActive || scrollerIsActive; - - // stop the timer - if (pressDelayTimer) { - killTimer(pressDelayTimer); - pressDelayTimer = 0; - } - // we still haven't even sent the press, so do it now - if (pressDelayEvent && mouseTarget && !scrollerIsActive) { - QScopedPointer<QMouseEvent> releaseEvent(copyMouseEvent(e)); - - qFGDebug() << "QFG: re-sending mouse press (due to release) for " << mouseTarget; - sendMouseEvent(pressDelayEvent.data(), UngrabMouseBefore); - - qFGDebug() << "QFG: faking mouse release (due to release) for " << mouseTarget; - sendMouseEvent(releaseEvent.data()); - - result = true; // consume this event - } else if (mouseTarget && scrollerIsActive) { - // we grabbed the mouse expicitly when the scroller became active, so undo that now - sendMouseEvent(0, UngrabMouseBefore); - } - pressDelayEvent.reset(0); - mouseTarget = 0; - return result; - } - - void scrollerWasIntercepted() - { - qFGDebug() << "QFG: deleting delayed mouse press, since scroller was only intercepted"; - if (pressDelayEvent) { - // we still haven't even sent the press, so just throw it away now - if (pressDelayTimer) { - killTimer(pressDelayTimer); - pressDelayTimer = 0; - } - pressDelayEvent.reset(0); - } - mouseTarget = 0; - } - - void scrollerBecameActive() - { - if (pressDelayEvent) { - // we still haven't even sent the press, so just throw it away now - qFGDebug() << "QFG: deleting delayed mouse press, since scroller is active now"; - if (pressDelayTimer) { - killTimer(pressDelayTimer); - pressDelayTimer = 0; - } - pressDelayEvent.reset(0); - mouseTarget = 0; - } else if (mouseTarget) { - // we did send a press, so we need to fake a release now - Qt::MouseButtons mouseButtons = QApplication::mouseButtons(); - - // release all pressed mouse buttons - /*for (int i = 0; i < 32; ++i) { - if (mouseButtons & (1 << i)) { - Qt::MouseButton b = static_cast<Qt::MouseButton>(1 << i); - mouseButtons &= ~b; - QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX); - - qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget; - QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, - b, mouseButtons, QApplication::keyboardModifiers()); - sendMouseEvent(&re); - } - }*/ - - QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX); - - qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget; - QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, - mouseButton, QApplication::mouseButtons() & ~mouseButton, - QApplication::keyboardModifiers()); - sendMouseEvent(&re, RegrabMouseAfterwards); - // don't clear the mouseTarget just yet, since we need to explicitly ungrab the mouse on release! - } - } - -protected: - void timerEvent(QTimerEvent *e) - { - if (e->timerId() == pressDelayTimer) { - if (pressDelayEvent && mouseTarget) { - qFGDebug() << "QFG: timer event: re-sending mouse press to " << mouseTarget; - sendMouseEvent(pressDelayEvent.data(), UngrabMouseBefore); - } - pressDelayEvent.reset(0); - - if (pressDelayTimer) { - killTimer(pressDelayTimer); - pressDelayTimer = 0; - } - } - } - - void sendMouseEvent(QMouseEvent *me, int flags = 0) - { - if (mouseTarget) { - sendingEvent = true; - -#ifndef QT_NO_GRAPHICSVIEW - QGraphicsItem *grabber = 0; - if (mouseTarget->parentWidget()) { - if (QGraphicsView *gv = qobject_cast<QGraphicsView *>(mouseTarget->parentWidget())) { - if (gv->scene()) - grabber = gv->scene()->mouseGrabberItem(); - } - } - - if (grabber && (flags & UngrabMouseBefore)) { - // GraphicsView Mouse Handling Workaround #1: - // we need to ungrab the mouse before re-sending the press, - // since the scene had already set the mouse grabber to the - // original (and consumed) event's receiver - qFGDebug() << "QFG: ungrabbing" << grabber; - grabber->ungrabMouse(); - } -#endif // QT_NO_GRAPHICSVIEW - - if (me) { - QMouseEvent copy(me->type(), mouseTarget->mapFromGlobal(me->globalPos()), me->globalPos(), me->button(), me->buttons(), me->modifiers()); - qt_sendSpontaneousEvent(mouseTarget, ©); - } - -#ifndef QT_NO_GRAPHICSVIEW - if (grabber && (flags & RegrabMouseAfterwards)) { - // GraphicsView Mouse Handling Workaround #2: - // we need to re-grab the mouse after sending a faked mouse - // release, since we still need the mouse moves for the gesture - // (the scene will clear the item's mouse grabber status on - // release). - qFGDebug() << "QFG: re-grabbing" << grabber; - grabber->grabMouse(); - } -#endif - sendingEvent = false; - } - } - - -private: - int pressDelayTimer; - QScopedPointer<QMouseEvent> pressDelayEvent; - bool sendingEvent; - Qt::MouseButton mouseButton; - QPointer<QWidget> mouseTarget; -}; - - -/*! - \internal - \class QFlickGesture - \since 4.8 - \brief The QFlickGesture class describes a flicking gesture made by the user. - \ingroup gestures - The QFlickGesture is more complex than the QPanGesture that uses QScroller and QScrollerProperties - to decide if it is triggered. - This gesture is reacting on touch event as compared to the QMouseFlickGesture. - - \sa {Gestures Programming}, QScroller, QScrollerProperties, QMouseFlickGesture -*/ - -/*! - \internal -*/ -QFlickGesture::QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent) - : QGesture(*new QFlickGesturePrivate, parent) -{ - d_func()->q_ptr = this; - d_func()->receiver = receiver; - d_func()->receiverScroller = (receiver && QScroller::hasScroller(receiver)) ? QScroller::scroller(receiver) : 0; - d_func()->button = button; -} - -QFlickGesture::~QFlickGesture() -{ } - -QFlickGesturePrivate::QFlickGesturePrivate() - : receiverScroller(0), button(Qt::NoButton), macIgnoreWheel(false) -{ } - - -// -// QFlickGestureRecognizer -// - - -QFlickGestureRecognizer::QFlickGestureRecognizer(Qt::MouseButton button) -{ - this->button = button; -} - -/*! \reimp - */ -QGesture *QFlickGestureRecognizer::create(QObject *target) -{ -#ifndef QT_NO_GRAPHICSVIEW - QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target); - if (go && button == Qt::NoButton) { - go->setAcceptTouchEvents(true); - } -#endif - return new QFlickGesture(target, button); -} - -/*! \internal - The recognize function detects a touch event suitable to start the attached QScroller. - The QFlickGesture will be triggered as soon as the scroller is no longer in the state - QScroller::Inactive or QScroller::Pressed. It will be finished or canceled - at the next QEvent::TouchEnd. - Note that the QScroller might continue scrolling (kinetically) at this point. - */ -QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state, - QObject *watched, - QEvent *event) -{ - Q_UNUSED(watched); - - static QElapsedTimer monotonicTimer; - if (!monotonicTimer.isValid()) - monotonicTimer.start(); - - QFlickGesture *q = static_cast<QFlickGesture *>(state); - QFlickGesturePrivate *d = q->d_func(); - - QScroller *scroller = d->receiverScroller; - if (!scroller) - return Ignore; // nothing to do without a scroller? - - QWidget *receiverWidget = qobject_cast<QWidget *>(d->receiver); -#ifndef QT_NO_GRAPHICSVIEW - QGraphicsObject *receiverGraphicsObject = qobject_cast<QGraphicsObject *>(d->receiver); -#endif - - // this is only set for events that we inject into the event loop via sendEvent() - if (PressDelayHandler::instance()->shouldEventBeIgnored(event)) { - //qFGDebug() << state << "QFG: ignored event: " << event->type(); - return Ignore; - } - - const QMouseEvent *me = 0; -#ifndef QT_NO_GRAPHICSVIEW - const QGraphicsSceneMouseEvent *gsme = 0; -#endif - const QTouchEvent *te = 0; - QPoint globalPos; - - // qFGDebug() << "FlickGesture "<<state<<"watched:"<<watched<<"receiver"<<d->receiver<<"event"<<event->type()<<"button"<<button; - - switch (event->type()) { - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseMove: - if (!receiverWidget) - return Ignore; - if (button != Qt::NoButton) { - me = static_cast<const QMouseEvent *>(event); - globalPos = me->globalPos(); - } - break; -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMousePress: - case QEvent::GraphicsSceneMouseRelease: - case QEvent::GraphicsSceneMouseMove: - if (!receiverGraphicsObject) - return Ignore; - if (button != Qt::NoButton) { - gsme = static_cast<const QGraphicsSceneMouseEvent *>(event); - globalPos = gsme->screenPos(); - } - break; -#endif - case QEvent::TouchBegin: - case QEvent::TouchEnd: - case QEvent::TouchUpdate: - if (button == Qt::NoButton) { - te = static_cast<const QTouchEvent *>(event); - if (!te->touchPoints().isEmpty()) - globalPos = te->touchPoints().at(0).screenPos().toPoint(); - } - break; - -#if defined(Q_WS_MAC) - // the only way to distinguish between real mouse wheels and wheel - // events generated by the native 2 finger swipe gesture is to listen - // for these events (according to Apple's Cocoa Event-Handling Guide) - - case QEvent::NativeGesture: { - QNativeGestureEvent *nge = static_cast<QNativeGestureEvent *>(event); - if (nge->gestureType == QNativeGestureEvent::GestureBegin) - d->macIgnoreWheel = true; - else if (nge->gestureType == QNativeGestureEvent::GestureEnd) - d->macIgnoreWheel = false; - break; - } -#endif - - // consume all wheel events if the scroller is active - case QEvent::Wheel: - if (d->macIgnoreWheel || (scroller->state() != QScroller::Inactive)) - return Ignore | ConsumeEventHint; - break; - - // consume all dbl click events if the scroller is active - case QEvent::MouseButtonDblClick: - if (scroller->state() != QScroller::Inactive) - return Ignore | ConsumeEventHint; - break; - - default: - break; - } - - if (!me -#ifndef QT_NO_GRAPHICSVIEW - && !gsme -#endif - && !te) // Neither mouse nor touch - return Ignore; - - // get the current pointer position in local coordinates. - QPointF point; - QScroller::Input inputType = (QScroller::Input) 0; - - switch (event->type()) { - case QEvent::MouseButtonPress: - if (me && me->button() == button && me->buttons() == button) { - point = me->globalPos(); - inputType = QScroller::InputPress; - } else if (me) { - scroller->stop(); - return CancelGesture; - } - break; - case QEvent::MouseButtonRelease: - if (me && me->button() == button) { - point = me->globalPos(); - inputType = QScroller::InputRelease; - } - break; - case QEvent::MouseMove: -#ifdef Q_OS_SYMBIAN - // Qt on Symbian tracks the button state internally, while Qt on Win/Mac/Unix - // relies on the windowing system to report the current buttons state. - if (me && (me->buttons() == button || !me->buttons())) { -#else - if (me && me->buttons() == button) { -#endif - point = me->globalPos(); - inputType = QScroller::InputMove; - } - break; - -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMousePress: - if (gsme && gsme->button() == button && gsme->buttons() == button) { - point = gsme->scenePos(); - inputType = QScroller::InputPress; - } else if (gsme) { - scroller->stop(); - return CancelGesture; - } - break; - case QEvent::GraphicsSceneMouseRelease: - if (gsme && gsme->button() == button) { - point = gsme->scenePos(); - inputType = QScroller::InputRelease; - } - break; - case QEvent::GraphicsSceneMouseMove: -#ifdef Q_OS_SYMBIAN - // Qt on Symbian tracks the button state internally, while Qt on Win/Mac/Unix - // relies on the windowing system to report the current buttons state. - if (gsme && (gsme->buttons() == button || !me->buttons())) { -#else - if (gsme && gsme->buttons() == button) { -#endif - point = gsme->scenePos(); - inputType = QScroller::InputMove; - } - break; -#endif - - case QEvent::TouchBegin: - inputType = QScroller::InputPress; - // fall through - case QEvent::TouchEnd: - if (!inputType) - inputType = QScroller::InputRelease; - // fallthrough - case QEvent::TouchUpdate: - if (!inputType) - inputType = QScroller::InputMove; - - if (te->deviceType() == QTouchEvent::TouchPad) { - if (te->touchPoints().count() != 2) // 2 fingers on pad - return Ignore; - - point = te->touchPoints().at(0).startScenePos() + - ((te->touchPoints().at(0).scenePos() - te->touchPoints().at(0).startScenePos()) + - (te->touchPoints().at(1).scenePos() - te->touchPoints().at(1).startScenePos())) / 2; - } else { // TouchScreen - if (te->touchPoints().count() != 1) // 1 finger on screen - return Ignore; - - point = te->touchPoints().at(0).scenePos(); - } - break; - - default: - break; - } - - // Check for an active scroller at globalPos - if (inputType == QScroller::InputPress) { - foreach (QScroller *as, QScroller::activeScrollers()) { - if (as != scroller) { - QRegion scrollerRegion; - - if (QWidget *w = qobject_cast<QWidget *>(as->target())) { - scrollerRegion = QRect(w->mapToGlobal(QPoint(0, 0)), w->size()); -#ifndef QT_NO_GRAPHICSVIEW - } else if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(as->target())) { - if (go->scene() && !go->scene()->views().isEmpty()) { - foreach (QGraphicsView *gv, go->scene()->views()) - scrollerRegion |= gv->mapFromScene(go->mapToScene(go->boundingRect())) - .translated(gv->mapToGlobal(QPoint(0, 0))); - } -#endif - } - // active scrollers always have priority - if (scrollerRegion.contains(globalPos)) - return Ignore; - } - } - } - - bool scrollerWasDragging = (scroller->state() == QScroller::Dragging); - bool scrollerWasScrolling = (scroller->state() == QScroller::Scrolling); - - if (inputType) { - if (QWidget *w = qobject_cast<QWidget *>(d->receiver)) - point = w->mapFromGlobal(point.toPoint()); -#ifndef QT_NO_GRAPHICSVIEW - else if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(d->receiver)) - point = go->mapFromScene(point); -#endif - - // inform the scroller about the new event - scroller->handleInput(inputType, point, monotonicTimer.elapsed()); - } - - // depending on the scroller state return the gesture state - Result result(0); - bool scrollerIsActive = (scroller->state() == QScroller::Dragging || - scroller->state() == QScroller::Scrolling); - - // Consume all mouse events while dragging or scrolling to avoid nasty - // side effects with Qt's standard widgets. - if ((me -#ifndef QT_NO_GRAPHICSVIEW - || gsme -#endif - ) && scrollerIsActive) - result |= ConsumeEventHint; - - // The only problem with this approach is that we consume the - // MouseRelease when we start the scrolling with a flick gesture, so we - // have to fake a MouseRelease "somewhere" to not mess with the internal - // states of Qt's widgets (a QPushButton would stay in 'pressed' state - // forever, if it doesn't receive a MouseRelease). - if (me -#ifndef QT_NO_GRAPHICSVIEW - || gsme -#endif - ) { - if (!scrollerWasDragging && !scrollerWasScrolling && scrollerIsActive) - PressDelayHandler::instance()->scrollerBecameActive(); - else if (scrollerWasScrolling && (scroller->state() == QScroller::Dragging || scroller->state() == QScroller::Inactive)) - PressDelayHandler::instance()->scrollerWasIntercepted(); - } - - if (!inputType) { - result |= Ignore; - } else { - switch (event->type()) { - case QEvent::MouseButtonPress: -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMousePress: -#endif - if (scroller->state() == QScroller::Pressed) { - int pressDelay = int(1000 * scroller->scrollerProperties().scrollMetric(QScrollerProperties::MousePressEventDelay).toReal()); - if (pressDelay > 0) { - result |= ConsumeEventHint; - - PressDelayHandler::instance()->pressed(event, pressDelay); - event->accept(); - } - } - // fall through - case QEvent::TouchBegin: - q->setHotSpot(globalPos); - result |= scrollerIsActive ? TriggerGesture : MayBeGesture; - break; - - case QEvent::MouseMove: -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMouseMove: -#endif - if (PressDelayHandler::instance()->isDelaying()) - result |= ConsumeEventHint; - // fall through - case QEvent::TouchUpdate: - result |= scrollerIsActive ? TriggerGesture : Ignore; - break; - -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMouseRelease: -#endif - case QEvent::MouseButtonRelease: - if (PressDelayHandler::instance()->released(event, scrollerWasDragging || scrollerWasScrolling, scrollerIsActive)) - result |= ConsumeEventHint; - // fall through - case QEvent::TouchEnd: - result |= scrollerIsActive ? FinishGesture : CancelGesture; - break; - - default: - result |= Ignore; - break; - } - } - return result; -} - - -/*! \reimp - */ -void QFlickGestureRecognizer::reset(QGesture *state) -{ - QGestureRecognizer::reset(state); -} - -QT_END_NAMESPACE - -#endif // QT_NO_GESTURES diff --git a/src/gui/util/qflickgesture_p.h b/src/gui/util/qflickgesture_p.h deleted file mode 100644 index 451b579..0000000 --- a/src/gui/util/qflickgesture_p.h +++ /dev/null @@ -1,113 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFLICKGESTURE_P_H -#define QFLICKGESTURE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qevent.h" -#include "qgesturerecognizer.h" -#include "private/qgesture_p.h" -#include "qscroller.h" -#include "qscopedpointer.h" - -#ifndef QT_NO_GESTURES - -QT_BEGIN_NAMESPACE - -class QFlickGesturePrivate; -class QGraphicsItem; - -class Q_GUI_EXPORT QFlickGesture : public QGesture -{ - Q_OBJECT - Q_DECLARE_PRIVATE(QFlickGesture) - -public: - QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent = 0); - ~QFlickGesture(); - - friend class QFlickGestureRecognizer; -}; - -class PressDelayHandler; - -class QFlickGesturePrivate : public QGesturePrivate -{ - Q_DECLARE_PUBLIC(QFlickGesture) -public: - QFlickGesturePrivate(); - - QPointer<QObject> receiver; - QScroller *receiverScroller; - Qt::MouseButton button; // NoButton == Touch - bool macIgnoreWheel; - static PressDelayHandler *pressDelayHandler; -}; - -class QFlickGestureRecognizer : public QGestureRecognizer -{ -public: - QFlickGestureRecognizer(Qt::MouseButton button); - - QGesture *create(QObject *target); - QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event); - void reset(QGesture *state); - -private: - Qt::MouseButton button; // NoButton == Touch -}; - -QT_END_NAMESPACE - -#endif // QT_NO_GESTURES - -#endif // QFLICKGESTURE_P_H diff --git a/src/gui/util/qscroller.cpp b/src/gui/util/qscroller.cpp deleted file mode 100644 index db128c1..0000000 --- a/src/gui/util/qscroller.cpp +++ /dev/null @@ -1,2059 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qevent.h" -#include "qwidget.h" -#include "qscroller.h" -#include "private/qflickgesture_p.h" -#include "private/qscroller_p.h" -#include "qscrollerproperties.h" -#include "private/qscrollerproperties_p.h" -#include "qnumeric.h" -#include "math.h" - -#include <QTime> -#include <QElapsedTimer> -#include <QMap> -#include <QApplication> -#include <QAbstractScrollArea> -#include <QGraphicsObject> -#include <QGraphicsScene> -#include <QGraphicsView> -#include <QDesktopWidget> -#include <QtCore/qmath.h> -#include <QtGui/qevent.h> -#include <qnumeric.h> - -#include <QtDebug> - -#if defined(Q_WS_X11) -# include "private/qt_x11_p.h" -#endif - - -QT_BEGIN_NAMESPACE - -bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); - -//#define QSCROLLER_DEBUG - -#ifdef QSCROLLER_DEBUG -# define qScrollerDebug qDebug -#else -# define qScrollerDebug while (false) qDebug -#endif - -QDebug &operator<<(QDebug &dbg, const QScrollerPrivate::ScrollSegment &s) -{ - dbg << "\n Time: start:" << s.startTime << " duration:" << s.deltaTime << " stop progress:" << s.stopProgress; - dbg << "\n Pos: start:" << s.startPos << " delta:" << s.deltaPos << " stop:" << s.stopPos; - dbg << "\n Curve: type:" << s.curve.type() << "\n"; - return dbg; -} - - -// a few helper operators to make the code below a lot more readable: -// otherwise a lot of ifs would have to be multi-line to check both the x -// and y coordinate separately. - -// returns true only if the abs. value of BOTH x and y are <= f -inline bool operator<=(const QPointF &p, qreal f) -{ - return (qAbs(p.x()) <= f) && (qAbs(p.y()) <= f); -} - -// returns true only if the abs. value of BOTH x and y are < f -inline bool operator<(const QPointF &p, qreal f) -{ - return (qAbs(p.x()) < f) && (qAbs(p.y()) < f); -} - -// returns true if the abs. value of EITHER x or y are >= f -inline bool operator>=(const QPointF &p, qreal f) -{ - return (qAbs(p.x()) >= f) || (qAbs(p.y()) >= f); -} - -// returns true if the abs. value of EITHER x or y are > f -inline bool operator>(const QPointF &p, qreal f) -{ - return (qAbs(p.x()) > f) || (qAbs(p.y()) > f); -} - -// returns a new point with both coordinates having the abs. value of the original one -inline QPointF qAbs(const QPointF &p) -{ - return QPointF(qAbs(p.x()), qAbs(p.y())); -} - -// returns a new point with all components of p1 multiplied by the corresponding components of p2 -inline QPointF operator*(const QPointF &p1, const QPointF &p2) -{ - return QPointF(p1.x() * p2.x(), p1.y() * p2.y()); -} - -// returns a new point with all components of p1 divided by the corresponding components of p2 -inline QPointF operator/(const QPointF &p1, const QPointF &p2) -{ - return QPointF(p1.x() / p2.x(), p1.y() / p2.y()); -} - -inline QPointF clampToRect(const QPointF &p, const QRectF &rect) -{ - qreal x = qBound(rect.left(), p.x(), rect.right()); - qreal y = qBound(rect.top(), p.y(), rect.bottom()); - return QPointF(x, y); -} - -// returns -1, 0 or +1 according to r being <0, ==0 or >0 -inline int qSign(qreal r) -{ - return (r < 0) ? -1 : ((r > 0) ? 1 : 0); -} - -// this version is not mathematically exact, but it just works for every -// easing curve type (even custom ones) - -static qreal differentialForProgress(const QEasingCurve &curve, qreal pos) -{ - const qreal dx = 0.01; - qreal left = (pos < qreal(0.5)) ? pos : pos - qreal(dx); - qreal right = (pos >= qreal(0.5)) ? pos : pos + qreal(dx); - qreal d = (curve.valueForProgress(right) - curve.valueForProgress(left)) / qreal(dx); - - //qScrollerDebug() << "differentialForProgress(type: " << curve.type() << ", pos: " << pos << ") = " << d; - - return d; -} - -// this version is not mathematically exact, but it just works for every -// easing curve type (even custom ones) - -static qreal progressForValue(const QEasingCurve &curve, qreal value) -{ - if (curve.type() >= QEasingCurve::InElastic && - curve.type() < QEasingCurve::Custom) { - qWarning("progressForValue(): QEasingCurves of type %d do not have an inverse, since they are not injective.", curve.type()); - return value; - } - if (value < qreal(0) || value > qreal(1)) - return value; - - qreal progress = value, left(0), right(1); - for (int iterations = 6; iterations; --iterations) { - qreal v = curve.valueForProgress(progress); - if (v < value) - left = progress; - else if (v > value) - right = progress; - else - break; - progress = (left + right) / qreal(2); - } - return progress; -} - - -#ifndef QT_NO_ANIMATION -class QScrollTimer : public QAbstractAnimation -{ -public: - QScrollTimer(QScrollerPrivate *_d) - : d(_d), ignoreUpdate(false), skip(0) - { } - - int duration() const - { - return -1; - } - - void start() - { - // QAbstractAnimation::start() will immediately call - // updateCurrentTime(), but our state is not set correctly yet - ignoreUpdate = true; - QAbstractAnimation::start(); - ignoreUpdate = false; - skip = 0; - } - -protected: - void updateCurrentTime(int /*currentTime*/) - { - if (!ignoreUpdate) { - if (++skip >= d->frameRateSkip()) { - skip = 0; - d->timerTick(); - } - } - } - -private: - QScrollerPrivate *d; - bool ignoreUpdate; - int skip; -}; -#endif // QT_NO_ANIMATION - -/*! - \class QScroller - \brief The QScroller class enables kinetic scrolling for any scrolling widget or graphics item. - \since 4.8 - - With kinetic scrolling, the user can push the widget in a given - direction and it will continue to scroll in this direction until it is - stopped either by the user or by friction. Aspects of inertia, friction - and other physical concepts can be changed in order to fine-tune an - intuitive user experience. - - The QScroller object is the object that stores the current position and - scrolling speed and takes care of updates. - QScroller can be triggered by a flick gesture - - \code - QWidget *w = ...; - QScroller::grabGesture(w, QScroller::LeftMouseButtonGesture); - \endcode - - or directly like this: - - \code - QWidget *w = ...; - QScroller *scroller = QScroller::scroller(w); - scroller->scrollTo(QPointF(100, 100)); - \endcode - - The scrolled QObjects receive a QScrollPrepareEvent whenever the scroller needs to - update its geometry information and a QScrollEvent whenever the content of the object should - actually be scrolled. - - The scroller uses the global QAbstractAnimation timer to generate its QScrollEvents. This - can be changed with QScrollerProperties::FrameRate on a per-QScroller basis. - - Several examples in the \c scroller examples directory show how QScroller, - QScrollEvent and the scroller gesture can be used. - - Even though this kinetic scroller has a large number of settings available via - QScrollerProperties, we recommend that you leave them all at their default, platform optimized - values. Before changing them you can experiment with the \c plot example in - the \c scroller examples directory. - - \sa QScrollEvent, QScrollPrepareEvent, QScrollerProperties -*/ - -typedef QMap<QObject *, QScroller *> ScrollerHash; -typedef QSet<QScroller *> ScrollerSet; - -Q_GLOBAL_STATIC(ScrollerHash, qt_allScrollers) -Q_GLOBAL_STATIC(ScrollerSet, qt_activeScrollers) - -/*! - Returns \c true if a QScroller object was already created for \a target; \c false otherwise. - - \sa scroller() -*/ -bool QScroller::hasScroller(QObject *target) -{ - return (qt_allScrollers()->value(target)); -} - -/*! - Returns the scroller for the given \a target. - As long as the object exists this function will always return the same QScroller instance. - If no QScroller exists for the \a target, one will implicitly be created. - At no point more than one QScroller will be active on an object. - - \sa hasScroller(), target() -*/ -QScroller *QScroller::scroller(QObject *target) -{ - if (!target) { - qWarning("QScroller::scroller() was called with a null target."); - return 0; - } - - if (qt_allScrollers()->contains(target)) - return qt_allScrollers()->value(target); - - QScroller *s = new QScroller(target); - qt_allScrollers()->insert(target, s); - return s; -} - -/*! - \overload - This is the const version of scroller(). -*/ -const QScroller *QScroller::scroller(const QObject *target) -{ - return scroller(const_cast<QObject*>(target)); -} - -/*! - Returns an application wide list of currently active QScroller objects. - Active QScroller objects are in a state() that is not QScroller::Inactive. - This function is useful when writing your own gesture recognizer. -*/ -QList<QScroller *> QScroller::activeScrollers() -{ - return qt_activeScrollers()->toList(); -} - -/*! - Returns the target object of this scroller. - \sa hasScroller(), scroller() - */ -QObject *QScroller::target() const -{ - Q_D(const QScroller); - return d->target; -} - -/*! - \fn QScroller::scrollerPropertiesChanged(const QScrollerProperties &newProperties); - - QScroller emits this signal whenever its scroller properties change. - \a newProperties are the new scroller properties. - - \sa scrollerProperties -*/ - - -/*! \property QScroller::scrollerProperties - \brief The scroller properties of this scroller. - The properties are used by the QScroller to determine its scrolling behavior. -*/ -QScrollerProperties QScroller::scrollerProperties() const -{ - Q_D(const QScroller); - return d->properties; -} - -void QScroller::setScrollerProperties(const QScrollerProperties &sp) -{ - Q_D(QScroller); - if (d->properties != sp) { - d->properties = sp; - emit scrollerPropertiesChanged(sp); - - // we need to force the recalculation here, since the overshootPolicy may have changed and - // existing segments may include an overshoot animation. - d->recalcScrollingSegments(true); - } -} - -#ifndef QT_NO_GESTURES - -/*! - Registers a custom scroll gesture recognizer, grabs it for the \a - target and returns the resulting gesture type. If \a scrollGestureType is - set to TouchGesture the gesture triggers on touch events. If it is set to - one of LeftMouseButtonGesture, RightMouseButtonGesture or - MiddleMouseButtonGesture it triggers on mouse events of the - corresponding button. - - Only one scroll gesture can be active on a single object at the same - time. If you call this function twice on the same object, it will - ungrab the existing gesture before grabbing the new one. - - \note To avoid unwanted side-effects, mouse events are consumed while - the gesture is triggered. Since the initial mouse press event is - not consumed, the gesture sends a fake mouse release event - at the global position \c{(INT_MIN, INT_MIN)}. This ensures that - internal states of the widget that received the original mouse press - are consistent. - - \sa ungrabGesture, grabbedGesture -*/ -Qt::GestureType QScroller::grabGesture(QObject *target, ScrollerGestureType scrollGestureType) -{ - // ensure that a scroller for target is created - QScroller *s = scroller(target); - if (!s) - return Qt::GestureType(0); - - QScrollerPrivate *sp = s->d_ptr; - if (sp->recognizer) - ungrabGesture(target); // ungrab the old gesture - - Qt::MouseButton button; - switch (scrollGestureType) { - case LeftMouseButtonGesture : button = Qt::LeftButton; break; - case RightMouseButtonGesture : button = Qt::RightButton; break; - case MiddleMouseButtonGesture: button = Qt::MiddleButton; break; - default : - case TouchGesture : button = Qt::NoButton; break; // NoButton == Touch - } - - sp->recognizer = new QFlickGestureRecognizer(button); - sp->recognizerType = QGestureRecognizer::registerRecognizer(sp->recognizer); - - if (target->isWidgetType()) { - QWidget *widget = static_cast<QWidget *>(target); - widget->grabGesture(sp->recognizerType); - if (scrollGestureType == TouchGesture) - widget->setAttribute(Qt::WA_AcceptTouchEvents); -#ifndef QT_NO_GRAPHICSVIEW - } else if (QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target)) { - if (scrollGestureType == TouchGesture) - go->setAcceptTouchEvents(true); - go->grabGesture(sp->recognizerType); -#endif // QT_NO_GRAPHICSVIEW - } - return sp->recognizerType; -} - -/*! - Returns the gesture type currently grabbed for the \a target or 0 if no - gesture is grabbed. - - \sa grabGesture, ungrabGesture -*/ -Qt::GestureType QScroller::grabbedGesture(QObject *target) -{ - QScroller *s = scroller(target); - if (s && s->d_ptr) - return s->d_ptr->recognizerType; - else - return Qt::GestureType(0); -} - -/*! - Ungrabs the gesture for the \a target. - Does nothing if no gesture is grabbed. - - \sa grabGesture, grabbedGesture -*/ -void QScroller::ungrabGesture(QObject *target) -{ - QScroller *s = scroller(target); - if (!s) - return; - - QScrollerPrivate *sp = s->d_ptr; - if (!sp->recognizer) - return; // nothing to do - - if (target->isWidgetType()) { - QWidget *widget = static_cast<QWidget *>(target); - widget->ungrabGesture(sp->recognizerType); -#ifndef QT_NO_GRAPHICSVIEW - } else if (QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target)) { - go->ungrabGesture(sp->recognizerType); -#endif - } - - QGestureRecognizer::unregisterRecognizer(sp->recognizerType); - // do not delete the recognizer. The QGestureManager is doing this. - sp->recognizer = 0; -} - -#endif // QT_NO_GESTURES - -/*! - \internal -*/ -QScroller::QScroller(QObject *target) - : d_ptr(new QScrollerPrivate(this, target)) -{ - Q_ASSERT(target); // you can't create a scroller without a target in any normal way - Q_D(QScroller); - d->init(); -} - -/*! - \internal -*/ -QScroller::~QScroller() -{ - Q_D(QScroller); -#ifndef QT_NO_GESTURES - QGestureRecognizer::unregisterRecognizer(d->recognizerType); - // do not delete the recognizer. The QGestureManager is doing this. - d->recognizer = 0; -#endif - qt_allScrollers()->remove(d->target); - qt_activeScrollers()->remove(this); - - delete d_ptr; -} - - -/*! - \fn QScroller::stateChanged(QScroller::State newState); - - QScroller emits this signal whenever the state changes. \a newState is the new State. - - \sa state -*/ - -/*! - \property QScroller::state - \brief the state of the scroller - - \sa QScroller::State -*/ -QScroller::State QScroller::state() const -{ - Q_D(const QScroller); - return d->state; -} - -/*! - Stops the scroller and resets its state back to Inactive. -*/ -void QScroller::stop() -{ - Q_D(QScroller); - if (d->state != Inactive) { - QPointF here = clampToRect(d->contentPosition, d->contentPosRange); - qreal snapX = d->nextSnapPos(here.x(), 0, Qt::Horizontal); - qreal snapY = d->nextSnapPos(here.y(), 0, Qt::Vertical); - QPointF snap = here; - if (!qIsNaN(snapX)) - snap.setX(snapX); - if (!qIsNaN(snapY)) - snap.setY(snapY); - d->contentPosition = snap; - d->overshootPosition = QPointF(0, 0); - - d->setState(Inactive); - } -} - -/*! - Returns the pixel per meter metric for the scrolled widget. - - The value is reported for both the x and y axis separately by using a QPointF. - - \note Please note that this value should be physically correct. The actual DPI settings - that Qt returns for the display may be reported wrongly on purpose by the underlying - windowing system, for example on Mac OS X or Maemo 5. -*/ -QPointF QScroller::pixelPerMeter() const -{ - Q_D(const QScroller); - QPointF ppm = d->pixelPerMeter; - -#ifndef QT_NO_GRAPHICSVIEW - if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(d->target)) { - QTransform viewtr; - //TODO: the first view isn't really correct - maybe use an additional field in the prepare event? - if (go->scene() && !go->scene()->views().isEmpty()) - viewtr = go->scene()->views().first()->viewportTransform(); - QTransform tr = go->deviceTransform(viewtr); - if (tr.isScaling()) { - QPointF p0 = tr.map(QPointF(0, 0)); - QPointF px = tr.map(QPointF(1, 0)); - QPointF py = tr.map(QPointF(0, 1)); - ppm.rx() /= QLineF(p0, px).length(); - ppm.ry() /= QLineF(p0, py).length(); - } - } -#endif // QT_NO_GRAPHICSVIEW - return ppm; -} - -/*! - Returns the current scrolling velocity in meter per second when the state is Scrolling or Dragging. - Returns a zero velocity otherwise. - - The velocity is reported for both the x and y axis separately by using a QPointF. - - \sa pixelPerMeter() -*/ -QPointF QScroller::velocity() const -{ - Q_D(const QScroller); - const QScrollerPropertiesPrivate *sp = d->properties.d.data(); - - switch (state()) { - case Dragging: - return d->releaseVelocity; - case Scrolling: { - QPointF vel; - qint64 now = d->monotonicTimer.elapsed(); - - if (!d->xSegments.isEmpty()) { - const QScrollerPrivate::ScrollSegment &s = d->xSegments.head(); - qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime); - qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress); - vel.setX(v); - } - - if (!d->ySegments.isEmpty()) { - const QScrollerPrivate::ScrollSegment &s = d->ySegments.head(); - qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime); - qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress); - vel.setY(v); - } - return vel; - } - default: - return QPointF(0, 0); - } -} - -/*! - Returns the estimated final position for the current scroll movement. - Returns the current position if the scroller state is not Scrolling. - The result is undefined when the scroller state is Inactive. - - The target position is in pixel. - - \sa pixelPerMeter(), scrollTo() -*/ -QPointF QScroller::finalPosition() const -{ - Q_D(const QScroller); - return QPointF(d->scrollingSegmentsEndPos(Qt::Horizontal), - d->scrollingSegmentsEndPos(Qt::Vertical)); -} - -/*! - Starts scrolling the widget so that point \a pos is at the top-left position in - the viewport. - - The behaviour when scrolling outside the valid scroll area is undefined. - In this case the scroller might or might not overshoot. - - The scrolling speed will be calculated so that the given position will - be reached after a platform-defined time span. - - \a pos is given in viewport coordinates. - - \sa ensureVisible() -*/ -void QScroller::scrollTo(const QPointF &pos) -{ - // we could make this adjustable via QScrollerProperties - scrollTo(pos, 300); -} - -/*! \overload - - This version will reach its destination position in \a scrollTime milliseconds. -*/ -void QScroller::scrollTo(const QPointF &pos, int scrollTime) -{ - Q_D(QScroller); - - if (d->state == Pressed || d->state == Dragging ) - return; - - // no need to resend a prepare event if we are already scrolling - if (d->state == Inactive && !d->prepareScrolling(QPointF())) - return; - - QPointF newpos = clampToRect(pos, d->contentPosRange); - qreal snapX = d->nextSnapPos(newpos.x(), 0, Qt::Horizontal); - qreal snapY = d->nextSnapPos(newpos.y(), 0, Qt::Vertical); - if (!qIsNaN(snapX)) - newpos.setX(snapX); - if (!qIsNaN(snapY)) - newpos.setY(snapY); - - qScrollerDebug() << "QScroller::scrollTo(req:" << pos << " [pix] / snap:" << newpos << ", " << scrollTime << " [ms])"; - - if (newpos == d->contentPosition + d->overshootPosition) - return; - - QPointF vel = velocity(); - - if (scrollTime < 0) - scrollTime = 0; - qreal time = qreal(scrollTime) / 1000; - - d->createScrollToSegments(vel.x(), time, newpos.x(), Qt::Horizontal, QScrollerPrivate::ScrollTypeScrollTo); - d->createScrollToSegments(vel.y(), time, newpos.y(), Qt::Vertical, QScrollerPrivate::ScrollTypeScrollTo); - - if (!scrollTime) - d->setContentPositionHelperScrolling(); - d->setState(scrollTime ? Scrolling : Inactive); -} - -/*! - Starts scrolling so that the rectangle \a rect is visible inside the - viewport with additional margins specified in pixels by \a xmargin and \a ymargin around - the rect. - - In cases where it is not possible to fit the rect plus margins inside the viewport the contents - are scrolled so that as much as possible is visible from \a rect. - - The scrolling speed is calculated so that the given position is reached after a platform-defined - time span. - - This function performs the actual scrolling by calling scrollTo(). - - \sa scrollTo -*/ -void QScroller::ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin) -{ - // we could make this adjustable via QScrollerProperties - ensureVisible(rect, xmargin, ymargin, 1000); -} - -/*! \overload - - This version will reach its destination position in \a scrollTime milliseconds. -*/ -void QScroller::ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin, int scrollTime) -{ - Q_D(QScroller); - - if (d->state == Pressed || d->state == Dragging ) - return; - - if (d->state == Inactive && !d->prepareScrolling(QPointF())) - return; - - // -- calculate the current pos (or the position after the current scroll) - QPointF startPos = d->contentPosition + d->overshootPosition; - startPos = QPointF(d->scrollingSegmentsEndPos(Qt::Horizontal), - d->scrollingSegmentsEndPos(Qt::Vertical)); - - QRectF marginRect(rect.x() - xmargin, rect.y() - ymargin, - rect.width() + 2 * xmargin, rect.height() + 2 * ymargin); - - QSizeF visible = d->viewportSize; - QRectF visibleRect(startPos, visible); - - qScrollerDebug() << "QScroller::ensureVisible(" << rect << " [pix], " << xmargin << " [pix], " << ymargin << " [pix], " << scrollTime << "[ms])"; - qScrollerDebug() << " --> content position:" << d->contentPosition; - - if (visibleRect.contains(marginRect)) - return; - - QPointF newPos = startPos; - - if (visibleRect.width() < rect.width()) { - // at least try to move the rect into view - if (rect.left() > visibleRect.left()) - newPos.setX(rect.left()); - else if (rect.right() < visibleRect.right()) - newPos.setX(rect.right() - visible.width()); - - } else if (visibleRect.width() < marginRect.width()) { - newPos.setX(rect.center().x() - visibleRect.width() / 2); - } else if (marginRect.left() > visibleRect.left()) { - newPos.setX(marginRect.left()); - } else if (marginRect.right() < visibleRect.right()) { - newPos.setX(marginRect.right() - visible.width()); - } - - if (visibleRect.height() < rect.height()) { - // at least try to move the rect into view - if (rect.top() > visibleRect.top()) - newPos.setX(rect.top()); - else if (rect.bottom() < visibleRect.bottom()) - newPos.setX(rect.bottom() - visible.height()); - - } else if (visibleRect.height() < marginRect.height()) { - newPos.setY(rect.center().y() - visibleRect.height() / 2); - } else if (marginRect.top() > visibleRect.top()) { - newPos.setY(marginRect.top()); - } else if (marginRect.bottom() < visibleRect.bottom()) { - newPos.setY(marginRect.bottom() - visible.height()); - } - - // clamp to maximum content position - newPos = clampToRect(newPos, d->contentPosRange); - if (newPos == startPos) - return; - - scrollTo(newPos, scrollTime); -} - -/*! This function resends the QScrollPrepareEvent. - Calling resendPrepareEvent triggers a QScrollPrepareEvent from the scroller. - This allows the receiver to re-set content position and content size while - scrolling. - Calling this function while in the Inactive state is useless as the prepare event - is sent again before scrolling starts. - */ -void QScroller::resendPrepareEvent() -{ - Q_D(QScroller); - d->prepareScrolling(d->pressPosition); -} - -/*! Set the snap positions for the horizontal axis to a list of \a positions. - This overwrites all previously set snap positions and also a previously - set snapping interval. - Snapping can be deactivated by setting an empty list of positions. - */ -void QScroller::setSnapPositionsX(const QList<qreal> &positions) -{ - Q_D(QScroller); - d->snapPositionsX = positions; - d->snapIntervalX = 0.0; - - d->recalcScrollingSegments(); -} - -/*! Set the snap positions for the horizontal axis to regular spaced intervals. - The first snap position is at \a first. The next at \a first + \a interval. - This can be used to implement a list header. - This overwrites all previously set snap positions and also a previously - set snapping interval. - Snapping can be deactivated by setting an interval of 0.0 - */ -void QScroller::setSnapPositionsX(qreal first, qreal interval) -{ - Q_D(QScroller); - d->snapFirstX = first; - d->snapIntervalX = interval; - d->snapPositionsX.clear(); - - d->recalcScrollingSegments(); -} - -/*! Set the snap positions for the vertical axis to a list of \a positions. - This overwrites all previously set snap positions and also a previously - set snapping interval. - Snapping can be deactivated by setting an empty list of positions. - */ -void QScroller::setSnapPositionsY(const QList<qreal> &positions) -{ - Q_D(QScroller); - d->snapPositionsY = positions; - d->snapIntervalY = 0.0; - - d->recalcScrollingSegments(); -} - -/*! Set the snap positions for the vertical axis to regular spaced intervals. - The first snap position is at \a first. The next at \a first + \a interval. - This overwrites all previously set snap positions and also a previously - set snapping interval. - Snapping can be deactivated by setting an interval of 0.0 - */ -void QScroller::setSnapPositionsY(qreal first, qreal interval) -{ - Q_D(QScroller); - d->snapFirstY = first; - d->snapIntervalY = interval; - d->snapPositionsY.clear(); - - d->recalcScrollingSegments(); -} - - - -// -------------- private ------------ - -QScrollerPrivate::QScrollerPrivate(QScroller *q, QObject *_target) - : target(_target) -#ifndef QT_NO_GESTURES - , recognizer(0) - , recognizerType(Qt::CustomGesture) -#endif - , state(QScroller::Inactive) - , firstScroll(true) - , pressTimestamp(0) - , lastTimestamp(0) - , snapFirstX(-1.0) - , snapIntervalX(0.0) - , snapFirstY(-1.0) - , snapIntervalY(0.0) -#ifndef QT_NO_ANIMATION - , scrollTimer(new QScrollTimer(this)) -#endif - , q_ptr(q) -{ - connect(target, SIGNAL(destroyed(QObject*)), this, SLOT(targetDestroyed())); -} - -void QScrollerPrivate::init() -{ - setDpiFromWidget(0); - monotonicTimer.start(); -} - -void QScrollerPrivate::sendEvent(QObject *o, QEvent *e) -{ - qt_sendSpontaneousEvent(o, e); -} - -const char *QScrollerPrivate::stateName(QScroller::State state) -{ - switch (state) { - case QScroller::Inactive: return "inactive"; - case QScroller::Pressed: return "pressed"; - case QScroller::Dragging: return "dragging"; - case QScroller::Scrolling: return "scrolling"; - default: return "(invalid)"; - } -} - -const char *QScrollerPrivate::inputName(QScroller::Input input) -{ - switch (input) { - case QScroller::InputPress: return "press"; - case QScroller::InputMove: return "move"; - case QScroller::InputRelease: return "release"; - default: return "(invalid)"; - } -} - -void QScrollerPrivate::targetDestroyed() -{ -#ifndef QT_NO_ANIMATION - scrollTimer->stop(); -#endif - delete q_ptr; -} - -void QScrollerPrivate::timerTick() -{ - struct timerevent { - QScroller::State state; - typedef void (QScrollerPrivate::*timerhandler_t)(); - timerhandler_t handler; - }; - - timerevent timerevents[] = { - { QScroller::Dragging, &QScrollerPrivate::timerEventWhileDragging }, - { QScroller::Scrolling, &QScrollerPrivate::timerEventWhileScrolling }, - }; - - for (int i = 0; i < int(sizeof(timerevents) / sizeof(*timerevents)); ++i) { - timerevent *te = timerevents + i; - - if (state == te->state) { - (this->*te->handler)(); - return; - } - } - -#ifndef QT_NO_ANIMATION - scrollTimer->stop(); -#endif -} - -/*! - This function is used by gesture recognizers to inform the scroller about a new input event. - The scroller changes its internal state() according to the input event and its attached - scroller properties. The scroller doesn't distinguish between the kind of input device the - event came from. Therefore the event needs to be split into the \a input type, a \a position and a - milli-second \a timestamp. The \a position needs to be in the target's coordinate system. - - The return value is \c true if the event should be consumed by the calling filter or \c false - if the event should be forwarded to the control. - - \note Using grabGesture() should be sufficient for most use cases. -*/ -bool QScroller::handleInput(Input input, const QPointF &position, qint64 timestamp) -{ - Q_D(QScroller); - - qScrollerDebug() << "QScroller::handleInput(" << input << ", " << d->stateName(d->state) << ", " << position << ", " << timestamp << ")"; - struct statechange { - State state; - Input input; - typedef bool (QScrollerPrivate::*inputhandler_t)(const QPointF &position, qint64 timestamp); - inputhandler_t handler; - }; - - statechange statechanges[] = { - { QScroller::Inactive, InputPress, &QScrollerPrivate::pressWhileInactive }, - { QScroller::Pressed, InputMove, &QScrollerPrivate::moveWhilePressed }, - { QScroller::Pressed, InputRelease, &QScrollerPrivate::releaseWhilePressed }, - { QScroller::Dragging, InputMove, &QScrollerPrivate::moveWhileDragging }, - { QScroller::Dragging, InputRelease, &QScrollerPrivate::releaseWhileDragging }, - { QScroller::Scrolling, InputPress, &QScrollerPrivate::pressWhileScrolling } - }; - - for (int i = 0; i < int(sizeof(statechanges) / sizeof(*statechanges)); ++i) { - statechange *sc = statechanges + i; - - if (d->state == sc->state && input == sc->input) - return (d->*sc->handler)(position - d->overshootPosition, timestamp); - } - return false; -} - -#if !defined(Q_WS_MAC) -// the Mac version is implemented in qscroller_mac.mm - -QPointF QScrollerPrivate::realDpi(int screen) -{ -# ifdef Q_WS_MAEMO_5 - Q_UNUSED(screen); - - // The DPI value is hardcoded to 96 on Maemo5: - // https://projects.maemo.org/bugzilla/show_bug.cgi?id=152525 - // This value (260) is only correct for the N900 though, but - // there's no way to get the real DPI at run time. - return QPointF(260, 260); - -# elif defined(Q_WS_X11) && !defined(QT_NO_XRANDR) - if (X11 && X11->use_xrandr && X11->ptrXRRSizes && X11->ptrXRRRootToScreen) { - int nsizes = 0; - // QDesktopWidget is based on Xinerama screens, which do not always - // correspond to RandR screens: NVidia's TwinView e.g. will show up - // as 2 screens in QDesktopWidget, but libXRandR will only see 1 screen. - // (although with the combined size of the Xinerama screens). - // Additionally, libXrandr will simply crash when calling XRRSizes - // for (the non-existent) screen 1 in this scenario. - Window root = RootWindow(X11->display, screen == -1 ? X11->defaultScreen : screen); - int randrscreen = (root != XNone) ? X11->ptrXRRRootToScreen(X11->display, root) : -1; - - XRRScreenSize *sizes = X11->ptrXRRSizes(X11->display, randrscreen == -1 ? 0 : randrscreen, &nsizes); - if (nsizes > 0 && sizes && sizes->width && sizes->height && sizes->mwidth && sizes->mheight) { - qScrollerDebug() << "XRandR DPI:" << QPointF(qreal(25.4) * qreal(sizes->width) / qreal(sizes->mwidth), - qreal(25.4) * qreal(sizes->height) / qreal(sizes->mheight)); - return QPointF(qreal(25.4) * qreal(sizes->width) / qreal(sizes->mwidth), - qreal(25.4) * qreal(sizes->height) / qreal(sizes->mheight)); - } - } -# endif - - QWidget *w = QApplication::desktop()->screen(screen); - return QPointF(w->physicalDpiX(), w->physicalDpiY()); -} - -#endif // !Q_WS_MAC - - -/*! \internal - Returns the resolution of the used screen. -*/ -QPointF QScrollerPrivate::dpi() const -{ - return pixelPerMeter * qreal(0.0254); -} - -/*! \internal - Sets the resolution used for scrolling. - This resolution is only used by the kinetic scroller. If you change this - then the scroller will behave quite different as a lot of the values are - given in physical distances (millimeter). -*/ -void QScrollerPrivate::setDpi(const QPointF &dpi) -{ - pixelPerMeter = dpi / qreal(0.0254); -} - -/*! \internal - Sets the dpi used for scrolling to the value of the widget. -*/ -void QScrollerPrivate::setDpiFromWidget(QWidget *widget) -{ - QDesktopWidget *dw = QApplication::desktop(); - setDpi(realDpi(widget ? dw->screenNumber(widget) : dw->primaryScreen())); -} - -/*! \internal - Updates the velocity during dragging. - Sets releaseVelocity. -*/ -void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 deltaTime) -{ - if (deltaTime <= 0) - return; - - Q_Q(QScroller); - QPointF ppm = q->pixelPerMeter(); - const QScrollerPropertiesPrivate *sp = properties.d.data(); - QPointF deltaPixel = deltaPixelRaw; - - qScrollerDebug() << "QScroller::updateVelocity(" << deltaPixelRaw << " [delta pix], " << deltaTime << " [delta ms])"; - - // faster than 2.5mm/ms seems bogus (that would be a screen height in ~20 ms) - if (((deltaPixelRaw / qreal(deltaTime)).manhattanLength() / ((ppm.x() + ppm.y()) / 2) * 1000) > qreal(2.5)) - deltaPixel = deltaPixelRaw * qreal(2.5) * ppm / 1000 / (deltaPixelRaw / qreal(deltaTime)).manhattanLength(); - - QPointF newv = -deltaPixel / qreal(deltaTime) * qreal(1000) / ppm; - // around 95% of all updates are in the [1..50] ms range, so make sure - // to scale the smoothing factor over that range: this way a 50ms update - // will have full impact, while 5ms update will only have a 10% impact. - qreal smoothing = sp->dragVelocitySmoothingFactor * qMin(qreal(deltaTime), qreal(50)) / qreal(50); - - // only smooth if we already have a release velocity and only if the - // user hasn't stopped to move his finger for more than 100ms - if ((releaseVelocity != QPointF(0, 0)) && (deltaTime < 100)) { - qScrollerDebug() << "SMOOTHED from " << newv << " to " << newv * smoothing + releaseVelocity * (qreal(1) - smoothing); - // smooth x or y only if the new velocity is either 0 or at least in - // the same direction of the release velocity - if (!newv.x() || (qSign(releaseVelocity.x()) == qSign(newv.x()))) - newv.setX(newv.x() * smoothing + releaseVelocity.x() * (qreal(1) - smoothing)); - if (!newv.y() || (qSign(releaseVelocity.y()) == qSign(newv.y()))) - newv.setY(newv.y() * smoothing + releaseVelocity.y() * (qreal(1) - smoothing)); - } else - qScrollerDebug() << "NO SMOOTHING to " << newv; - - releaseVelocity.setX(qBound(-sp->maximumVelocity, newv.x(), sp->maximumVelocity)); - releaseVelocity.setY(qBound(-sp->maximumVelocity, newv.y(), sp->maximumVelocity)); - - qScrollerDebug() << " --> new velocity:" << releaseVelocity; -} - -void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, qreal startPos, qreal deltaPos, qreal stopPos, QEasingCurve::Type curve, Qt::Orientation orientation) -{ - if (startPos == stopPos || deltaPos == 0) - return; - - ScrollSegment s; - if (orientation == Qt::Horizontal && !xSegments.isEmpty()) - s.startTime = xSegments.last().startTime + xSegments.last().deltaTime * xSegments.last().stopProgress; - else if (orientation == Qt::Vertical && !ySegments.isEmpty()) - s.startTime = ySegments.last().startTime + ySegments.last().deltaTime * ySegments.last().stopProgress; - else - s.startTime = monotonicTimer.elapsed(); - - s.startPos = startPos; - s.deltaPos = deltaPos; - s.stopPos = stopPos; - s.deltaTime = deltaTime * 1000; - s.stopProgress = stopProgress; - s.curve.setType(curve); - s.type = type; - - if (orientation == Qt::Horizontal) - xSegments.enqueue(s); - else - ySegments.enqueue(s); - - qScrollerDebug() << "+++ Added a new ScrollSegment: " << s; -} - - -/*! \internal - Clears the old segments and recalculates them if the current segments are not longer valid -*/ -void QScrollerPrivate::recalcScrollingSegments(bool forceRecalc) -{ - Q_Q(QScroller); - QPointF ppm = q->pixelPerMeter(); - - releaseVelocity = q->velocity(); - - if (forceRecalc || !scrollingSegmentsValid(Qt::Horizontal)) - createScrollingSegments(releaseVelocity.x(), contentPosition.x() + overshootPosition.x(), ppm.x(), Qt::Horizontal); - - if (forceRecalc || !scrollingSegmentsValid(Qt::Vertical)) - createScrollingSegments(releaseVelocity.y(), contentPosition.y() + overshootPosition.y(), ppm.y(), Qt::Vertical); -} - -/*! \internal - Returns the end position after the current scroll has finished. -*/ -qreal QScrollerPrivate::scrollingSegmentsEndPos(Qt::Orientation orientation) const -{ - if (orientation == Qt::Horizontal) { - if (xSegments.isEmpty()) - return contentPosition.x() + overshootPosition.x(); - else - return xSegments.last().stopPos; - } else { - if (ySegments.isEmpty()) - return contentPosition.y() + overshootPosition.y(); - else - return ySegments.last().stopPos; - } -} - -/*! \internal - Checks if the scroller segment end in a valid position. -*/ -bool QScrollerPrivate::scrollingSegmentsValid(Qt::Orientation orientation) -{ - QQueue<ScrollSegment> *segments; - qreal minPos; - qreal maxPos; - - if (orientation == Qt::Horizontal) { - segments = &xSegments; - minPos = contentPosRange.left(); - maxPos = contentPosRange.right(); - } else { - segments = &ySegments; - minPos = contentPosRange.top(); - maxPos = contentPosRange.bottom(); - } - - if (segments->isEmpty()) - return true; - - const ScrollSegment &last = segments->last(); - qreal stopPos = last.stopPos; - - if (last.type == ScrollTypeScrollTo) - return true; // scrollTo is always valid - - if (last.type == ScrollTypeOvershoot && - (stopPos != minPos && stopPos != maxPos)) - return false; - - if (stopPos < minPos || stopPos > maxPos) - return false; - - if (stopPos == minPos || stopPos == maxPos) // the begin and the end of the list are always ok - return true; - - qreal nextSnap = nextSnapPos(stopPos, 0, orientation); - if (!qIsNaN(nextSnap) && stopPos != nextSnap) - return false; - - return true; -} - -/*! \internal - Creates the sections needed to scroll to the specific \a endPos to the segments queue. -*/ -void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, Qt::Orientation orientation, ScrollType type) -{ - Q_UNUSED(v); - - if (orientation == Qt::Horizontal) - xSegments.clear(); - else - ySegments.clear(); - - qScrollerDebug() << "+++ createScrollToSegments: t:" << deltaTime << "ep:" << endPos << "o:" << int(orientation); - - const QScrollerPropertiesPrivate *sp = properties.d.data(); - - qreal startPos = (orientation == Qt::Horizontal) ? contentPosition.x() + overshootPosition.x() - : contentPosition.y() + overshootPosition.y(); - qreal deltaPos = (endPos - startPos) / 2; - - pushSegment(type, deltaTime * qreal(0.3), qreal(1.0), startPos, deltaPos, startPos + deltaPos, QEasingCurve::InQuad, orientation); - pushSegment(type, deltaTime * qreal(0.7), qreal(1.0), startPos + deltaPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation); -} - -/*! \internal -*/ -void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, qreal ppm, Qt::Orientation orientation) -{ - const QScrollerPropertiesPrivate *sp = properties.d.data(); - - QScrollerProperties::OvershootPolicy policy; - qreal minPos; - qreal maxPos; - qreal viewSize; - - if (orientation == Qt::Horizontal) { - xSegments.clear(); - policy = sp->hOvershootPolicy; - minPos = contentPosRange.left(); - maxPos = contentPosRange.right(); - viewSize = viewportSize.width(); - } else { - ySegments.clear(); - policy = sp->vOvershootPolicy; - minPos = contentPosRange.top(); - maxPos = contentPosRange.bottom(); - viewSize = viewportSize.height(); - } - - bool alwaysOvershoot = (policy == QScrollerProperties::OvershootAlwaysOn); - bool noOvershoot = (policy == QScrollerProperties::OvershootAlwaysOff) || !sp->overshootScrollDistanceFactor; - bool canOvershoot = !noOvershoot && (alwaysOvershoot || maxPos); - - qScrollerDebug() << "+++ createScrollingSegments: s:" << startPos << "maxPos:" << maxPos << "o:" << int(orientation); - - qScrollerDebug() << "v = " << v << ", decelerationFactor = " << sp->decelerationFactor << ", curveType = " << sp->scrollingCurve.type(); - - // This is only correct for QEasingCurve::OutQuad (linear velocity, - // constant deceleration), but the results look and feel ok for OutExpo - // and OutSine as well - - // v(t) = deltaTime * a * 0.5 * differentialForProgress(t / deltaTime) - // v(0) = vrelease - // v(deltaTime) = 0 - // deltaTime = (2 * vrelease) / (a * differntial(0)) - - // pos(t) = integrate(v(t)dt) - // pos(t) = vrelease * t - 0.5 * a * t * t - // pos(t) = deltaTime * a * 0.5 * progress(t / deltaTime) * deltaTime - // deltaPos = pos(deltaTime) - - qreal deltaTime = (qreal(2) * qAbs(v)) / (sp->decelerationFactor * differentialForProgress(sp->scrollingCurve, 0)); - qreal deltaPos = qSign(v) * deltaTime * deltaTime * qreal(0.5) * sp->decelerationFactor * ppm; - qreal endPos = startPos + deltaPos; - - qScrollerDebug() << " Real Delta:" << deltaPos; - - // -- determine snap points - qreal nextSnap = nextSnapPos(endPos, 0, orientation); - qreal lowerSnapPos = nextSnapPos(startPos, -1, orientation); - qreal higherSnapPos = nextSnapPos(startPos, 1, orientation); - - qScrollerDebug() << " Real Delta:" << lowerSnapPos <<"-"<<nextSnap <<"-"<<higherSnapPos; - - // - check if we can reach another snap point - if (nextSnap > higherSnapPos || qIsNaN(higherSnapPos)) - higherSnapPos = nextSnap; - if (nextSnap < lowerSnapPos || qIsNaN(lowerSnapPos)) - lowerSnapPos = nextSnap; - - // -- check if are in overshoot and end in overshoot - if ((startPos < minPos && endPos < minPos) || - (startPos > maxPos && endPos > maxPos)) { - qreal stopPos = endPos < minPos ? minPos : maxPos; - qreal oDeltaTime = sp->overshootScrollTime; - - pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), startPos, stopPos - startPos, stopPos, sp->scrollingCurve.type(), orientation); - return; - } - - if (qAbs(v) < sp->minimumVelocity) { - - qScrollerDebug() << "### below minimum Vel" << orientation; - - // - no snap points or already at one - if (qIsNaN(nextSnap) || nextSnap == startPos) - return; // nothing to do, no scrolling needed. - - // - decide which point to use - - qreal snapDistance = higherSnapPos - lowerSnapPos; - - qreal pressDistance = (orientation == Qt::Horizontal) ? - lastPosition.x() - pressPosition.x() : - lastPosition.y() - pressPosition.y(); - - // if not dragged far enough, pick the next snap point. - if (sp->snapPositionRatio == 0.0 || qAbs(pressDistance / sp->snapPositionRatio) > snapDistance) - endPos = nextSnap; - else if (pressDistance < 0.0) - endPos = lowerSnapPos; - else - endPos = higherSnapPos; - - deltaPos = endPos - startPos; - qreal midPos = startPos + deltaPos * qreal(0.3); - pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.3), qreal(1.0), startPos, midPos - startPos, midPos, QEasingCurve::InQuad, orientation); - pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.7), qreal(1.0), midPos, endPos - midPos, endPos, sp->scrollingCurve.type(), orientation); - return; - } - - // - go to the next snappoint if there is one - if (v > 0 && !qIsNaN(higherSnapPos)) { - // change the time in relation to the changed end position - if (endPos - startPos) - deltaTime *= qAbs((higherSnapPos - startPos) / (endPos - startPos)); - if (deltaTime > sp->snapTime) - deltaTime = sp->snapTime; - endPos = higherSnapPos; - - } else if (v < 0 && !qIsNaN(lowerSnapPos)) { - // change the time in relation to the changed end position - if (endPos - startPos) - deltaTime *= qAbs((lowerSnapPos - startPos) / (endPos - startPos)); - if (deltaTime > sp->snapTime) - deltaTime = sp->snapTime; - endPos = lowerSnapPos; - - // -- check if we are overshooting - } else if (endPos < minPos || endPos > maxPos) { - qreal stopPos = endPos < minPos ? minPos : maxPos; - - qScrollerDebug() << "Overshoot: delta:" << (stopPos - startPos); - - qreal stopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos - startPos) / deltaPos)); - - if (!canOvershoot) { - qScrollerDebug() << "Overshoot stopp:" << stopProgress; - - pushSegment(ScrollTypeFlick, deltaTime, stopProgress, startPos, endPos, stopPos, sp->scrollingCurve.type(), orientation); - } else { - qreal oDeltaTime = sp->overshootScrollTime; - qreal oStopProgress = qMin(stopProgress + oDeltaTime * qreal(0.3) / deltaTime, qreal(1)); - qreal oDistance = startPos + deltaPos * sp->scrollingCurve.valueForProgress(oStopProgress) - stopPos; - qreal oMaxDistance = qSign(oDistance) * (viewSize * sp->overshootScrollDistanceFactor); - - qScrollerDebug() << "1 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress; - - if (qAbs(oDistance) > qAbs(oMaxDistance)) { - oStopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos + oMaxDistance - startPos) / deltaPos)); - oDistance = oMaxDistance; - qScrollerDebug() << "2 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress; - } - - pushSegment(ScrollTypeFlick, deltaTime, oStopProgress, startPos, deltaPos, stopPos + oDistance, sp->scrollingCurve.type(), orientation); - pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), stopPos + oDistance, -oDistance, stopPos, sp->scrollingCurve.type(), orientation); - } - return; - } - - pushSegment(ScrollTypeFlick, deltaTime, qreal(1.0), startPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation); -} - - -/*! \internal - Prepares scrolling by sending a QScrollPrepareEvent to the receiver widget. - Returns true if the scrolling was accepted and a target was returned. -*/ -bool QScrollerPrivate::prepareScrolling(const QPointF &position) -{ - QScrollPrepareEvent spe(position); - spe.ignore(); - sendEvent(target, &spe); - - qScrollerDebug() << "QScrollPrepareEvent returned from" << target << "with" << spe.isAccepted() << "mcp:" << spe.contentPosRange() << "cp:" << spe.contentPos(); - if (spe.isAccepted()) { - QPointF oldContentPos = contentPosition + overshootPosition; - QPointF contentDelta = spe.contentPos() - oldContentPos; - - viewportSize = spe.viewportSize(); - contentPosRange = spe.contentPosRange(); - if (contentPosRange.width() < 0) - contentPosRange.setWidth(0); - if (contentPosRange.height() < 0) - contentPosRange.setHeight(0); - contentPosition = clampToRect(spe.contentPos(), contentPosRange); - overshootPosition = spe.contentPos() - contentPosition; - - // - check if the content position was moved - if (contentDelta != QPointF(0, 0)) { - // need to correct all segments - for (int i = 0; i < xSegments.count(); i++) - xSegments[i].startPos -= contentDelta.x(); - - for (int i = 0; i < ySegments.count(); i++) - ySegments[i].startPos -= contentDelta.y(); - } - - if (QWidget *w = qobject_cast<QWidget *>(target)) - setDpiFromWidget(w); -#ifndef QT_NO_GRAPHICSVIEW - if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(target)) { - //TODO: the first view isn't really correct - maybe use an additional field in the prepare event? - if (go->scene() && !go->scene()->views().isEmpty()) - setDpiFromWidget(go->scene()->views().first()); - } -#endif - - if (state == QScroller::Scrolling) { - recalcScrollingSegments(); - } - return true; - } - - return false; -} - -void QScrollerPrivate::handleDrag(const QPointF &position, qint64 timestamp) -{ - const QScrollerPropertiesPrivate *sp = properties.d.data(); - - QPointF deltaPixel = position - lastPosition; - qint64 deltaTime = timestamp - lastTimestamp; - - if (sp->axisLockThreshold) { - int dx = qAbs(deltaPixel.x()); - int dy = qAbs(deltaPixel.y()); - if (dx || dy) { - bool vertical = (dy > dx); - qreal alpha = qreal(vertical ? dx : dy) / qreal(vertical ? dy : dx); - //qScrollerDebug() << "QScroller::handleDrag() -- axis lock:" << alpha << " / " << axisLockThreshold << "- isvertical:" << vertical << "- dx:" << dx << "- dy:" << dy; - if (alpha <= sp->axisLockThreshold) { - if (vertical) - deltaPixel.setX(0); - else - deltaPixel.setY(0); - } - } - } - - // calculate velocity (if the user would release the mouse NOW) - updateVelocity(deltaPixel, deltaTime); - - // restrict velocity, if content is not scrollable - QRectF max = contentPosRange; - bool canScrollX = (max.width() > 0) || (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn); - bool canScrollY = (max.height() > 0) || (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn); - - if (!canScrollX) { - deltaPixel.setX(0); - releaseVelocity.setX(0); - } - if (!canScrollY) { - deltaPixel.setY(0); - releaseVelocity.setY(0); - } - -// if (firstDrag) { -// // Do not delay the first drag -// setContentPositionHelper(q->contentPosition() - overshootDistance - deltaPixel); -// dragDistance = QPointF(0, 0); -// } else { - dragDistance += deltaPixel; -// } -//qScrollerDebug() << "######################" << deltaPixel << position.y() << lastPosition.y(); - if (canScrollX) - lastPosition.setX(position.x()); - if (canScrollY) - lastPosition.setY(position.y()); - lastTimestamp = timestamp; -} - -bool QScrollerPrivate::pressWhileInactive(const QPointF &position, qint64 timestamp) -{ - if (prepareScrolling(position)) { - const QScrollerPropertiesPrivate *sp = properties.d.data(); - - if (!contentPosRange.isNull() || - (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn) || - (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn)) { - - lastPosition = pressPosition = position; - lastTimestamp = pressTimestamp = timestamp; - setState(QScroller::Pressed); - } - } - return false; -} - -bool QScrollerPrivate::releaseWhilePressed(const QPointF &, qint64) -{ - if (overshootPosition != QPointF(0.0, 0.0)) { - setState(QScroller::Scrolling); - return true; - } else { - setState(QScroller::Inactive); - return false; - } -} - -bool QScrollerPrivate::moveWhilePressed(const QPointF &position, qint64 timestamp) -{ - Q_Q(QScroller); - const QScrollerPropertiesPrivate *sp = properties.d.data(); - QPointF ppm = q->pixelPerMeter(); - - QPointF deltaPixel = position - pressPosition; - - bool moveAborted = false; - bool moveStarted = (((deltaPixel / ppm).manhattanLength()) > sp->dragStartDistance); - - // check the direction of the mouse drag and abort if it's too much in the wrong direction. - if (moveStarted) { - QRectF max = contentPosRange; - bool canScrollX = (max.width() > 0); - bool canScrollY = (max.height() > 0); - - if (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn) - canScrollX = true; - if (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn) - canScrollY = true; - - if (qAbs(deltaPixel.x() / ppm.x()) < qAbs(deltaPixel.y() / ppm.y())) { - if (!canScrollY) - moveAborted = true; - } else { - if (!canScrollX) - moveAborted = true; - } - } - - if (moveAborted) { - setState(QScroller::Inactive); - moveStarted = false; - - } else if (moveStarted) { - setState(QScroller::Dragging); - - // subtract the dragStartDistance - deltaPixel = deltaPixel - deltaPixel * (sp->dragStartDistance / deltaPixel.manhattanLength()); - - if (deltaPixel != QPointF(0, 0)) { - // handleDrag updates lastPosition, lastTimestamp and velocity - handleDrag(pressPosition + deltaPixel, timestamp); - } - } - return moveStarted; -} - -bool QScrollerPrivate::moveWhileDragging(const QPointF &position, qint64 timestamp) -{ - // handleDrag updates lastPosition, lastTimestamp and velocity - handleDrag(position, timestamp); - return true; -} - -void QScrollerPrivate::timerEventWhileDragging() -{ - if (dragDistance != QPointF(0, 0)) { - qScrollerDebug() << "QScroller::timerEventWhileDragging() -- dragDistance:" << dragDistance; - - setContentPositionHelperDragging(-dragDistance); - dragDistance = QPointF(0, 0); - } -} - -bool QScrollerPrivate::releaseWhileDragging(const QPointF &position, qint64 timestamp) -{ - Q_Q(QScroller); - const QScrollerPropertiesPrivate *sp = properties.d.data(); - - // handleDrag updates lastPosition, lastTimestamp and velocity - handleDrag(position, timestamp); - - // check if we moved at all - this can happen if you stop a running - // scroller with a press and release shortly afterwards - QPointF deltaPixel = position - pressPosition; - if (((deltaPixel / q->pixelPerMeter()).manhattanLength()) > sp->dragStartDistance) { - - // handle accelerating flicks - if ((oldVelocity != QPointF(0, 0)) && sp->acceleratingFlickMaximumTime && - ((timestamp - pressTimestamp) < qint64(sp->acceleratingFlickMaximumTime * 1000))) { - - // - determine if the direction was changed - int signX = 0, signY = 0; - if (releaseVelocity.x()) - signX = (releaseVelocity.x() > 0) == (oldVelocity.x() > 0) ? 1 : -1; - if (releaseVelocity.y()) - signY = (releaseVelocity.y() > 0) == (oldVelocity.y() > 0) ? 1 : -1; - - if (signX > 0) - releaseVelocity.setX(qBound(-sp->maximumVelocity, - oldVelocity.x() * sp->acceleratingFlickSpeedupFactor, - sp->maximumVelocity)); - if (signY > 0) - releaseVelocity.setY(qBound(-sp->maximumVelocity, - oldVelocity.y() * sp->acceleratingFlickSpeedupFactor, - sp->maximumVelocity)); - } - } - - QPointF ppm = q->pixelPerMeter(); - createScrollingSegments(releaseVelocity.x(), contentPosition.x() + overshootPosition.x(), ppm.x(), Qt::Horizontal); - createScrollingSegments(releaseVelocity.y(), contentPosition.y() + overshootPosition.y(), ppm.y(), Qt::Vertical); - - qScrollerDebug() << "QScroller::releaseWhileDragging() -- velocity:" << releaseVelocity << "-- minimum velocity:" << sp->minimumVelocity << "overshoot" << overshootPosition; - - if (xSegments.isEmpty() && ySegments.isEmpty()) - setState(QScroller::Inactive); - else - setState(QScroller::Scrolling); - - return true; -} - -void QScrollerPrivate::timerEventWhileScrolling() -{ - qScrollerDebug() << "QScroller::timerEventWhileScrolling()"; - - setContentPositionHelperScrolling(); - if (xSegments.isEmpty() && ySegments.isEmpty()) - setState(QScroller::Inactive); -} - -bool QScrollerPrivate::pressWhileScrolling(const QPointF &position, qint64 timestamp) -{ - Q_Q(QScroller); - - if ((q->velocity() <= properties.d->maximumClickThroughVelocity) && - (overshootPosition == QPointF(0.0, 0.0))) { - setState(QScroller::Inactive); - return false; - } else { - lastPosition = pressPosition = position; - lastTimestamp = pressTimestamp = timestamp; - setState(QScroller::Pressed); - setState(QScroller::Dragging); - return true; - } -} - -/*! \internal - This function handles all state changes of the scroller. -*/ -void QScrollerPrivate::setState(QScroller::State newstate) -{ - Q_Q(QScroller); - bool sendLastScroll = false; - - if (state == newstate) - return; - - qScrollerDebug() << q << "QScroller::setState(" << stateName(newstate) << ")"; - - switch (newstate) { - case QScroller::Inactive: -#ifndef QT_NO_ANIMATION - scrollTimer->stop(); -#endif - - // send the last scroll event (but only after the current state change was finished) - if (!firstScroll) - sendLastScroll = true; - - releaseVelocity = QPointF(0, 0); - break; - - case QScroller::Pressed: -#ifndef QT_NO_ANIMATION - scrollTimer->stop(); -#endif - - oldVelocity = releaseVelocity; - releaseVelocity = QPointF(0, 0); - break; - - case QScroller::Dragging: - dragDistance = QPointF(0, 0); -#ifndef QT_NO_ANIMATION - if (state == QScroller::Pressed) - scrollTimer->start(); -#endif - break; - - case QScroller::Scrolling: -#ifndef QT_NO_ANIMATION - scrollTimer->start(); -#endif - break; - } - - qSwap(state, newstate); - - if (sendLastScroll) { - QScrollEvent se(contentPosition, overshootPosition, QScrollEvent::ScrollFinished); - sendEvent(target, &se); - firstScroll = true; - } - if (state == QScroller::Dragging || state == QScroller::Scrolling) - qt_activeScrollers()->insert(q); - else - qt_activeScrollers()->remove(q); - emit q->stateChanged(state); -} - - -/*! \internal - Helps when setting the content position. - It will try to move the content by the requested delta but stop in case - when we are coming back from an overshoot or a scrollTo. - It will also indicate a new overshooting condition by the overshootX and oversthootY flags. - - In this cases it will reset the velocity variables and other flags. - - Also keeps track of the current over-shooting value in overshootPosition. - - \a deltaPos is the amount of pixels the current content position should be moved -*/ -void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos) -{ - Q_Q(QScroller); - QPointF ppm = q->pixelPerMeter(); - const QScrollerPropertiesPrivate *sp = properties.d.data(); - QPointF v = q->velocity(); - - if (sp->overshootDragResistanceFactor) - overshootPosition /= sp->overshootDragResistanceFactor; - - QPointF oldPos = contentPosition + overshootPosition; - QPointF newPos = oldPos + deltaPos; - - qScrollerDebug() << "QScroller::setContentPositionHelperDragging(" << deltaPos << " [pix])"; - qScrollerDebug() << " --> overshoot:" << overshootPosition << "- old pos:" << oldPos << "- new pos:" << newPos; - - QPointF oldClampedPos = clampToRect(oldPos, contentPosRange); - QPointF newClampedPos = clampToRect(newPos, contentPosRange); - - // --- handle overshooting and stop if the coordinate is going back inside the normal area - bool alwaysOvershootX = (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOn); - bool alwaysOvershootY = (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOn); - bool noOvershootX = (sp->hOvershootPolicy == QScrollerProperties::OvershootAlwaysOff) || - ((state == QScroller::Dragging) && !sp->overshootDragResistanceFactor) || - !sp->overshootDragDistanceFactor; - bool noOvershootY = (sp->vOvershootPolicy == QScrollerProperties::OvershootAlwaysOff) || - ((state == QScroller::Dragging) && !sp->overshootDragResistanceFactor) || - !sp->overshootDragDistanceFactor; - bool canOvershootX = !noOvershootX && (alwaysOvershootX || contentPosRange.width()); - bool canOvershootY = !noOvershootY && (alwaysOvershootY || contentPosRange.height()); - - qreal oldOvershootX = (canOvershootX) ? oldPos.x() - oldClampedPos.x() : 0; - qreal oldOvershootY = (canOvershootY) ? oldPos.y() - oldClampedPos.y() : 0; - - qreal newOvershootX = (canOvershootX) ? newPos.x() - newClampedPos.x() : 0; - qreal newOvershootY = (canOvershootY) ? newPos.y() - newClampedPos.y() : 0; - - qreal maxOvershootX = viewportSize.width() * sp->overshootDragDistanceFactor; - qreal maxOvershootY = viewportSize.height() * sp->overshootDragDistanceFactor; - - qScrollerDebug() << " --> noOs:" << noOvershootX << "drf:" << sp->overshootDragResistanceFactor << "mdf:" << sp->overshootScrollDistanceFactor << "ossP:"<<sp->hOvershootPolicy; - qScrollerDebug() << " --> canOS:" << canOvershootX << "newOS:" << newOvershootX << "maxOS:" << maxOvershootX; - - if (sp->overshootDragResistanceFactor) { - oldOvershootX *= sp->overshootDragResistanceFactor; - oldOvershootY *= sp->overshootDragResistanceFactor; - newOvershootX *= sp->overshootDragResistanceFactor; - newOvershootY *= sp->overshootDragResistanceFactor; - } - - // -- stop at the maximum overshoot distance - - newOvershootX = qBound(-maxOvershootX, newOvershootX, maxOvershootX); - newOvershootY = qBound(-maxOvershootY, newOvershootY, maxOvershootY); - - overshootPosition.setX(newOvershootX); - overshootPosition.setY(newOvershootY); - contentPosition = newClampedPos; - - QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted : QScrollEvent::ScrollUpdated); - sendEvent(target, &se); - firstScroll = false; - - qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition << - "- overshoot x/y?:" << overshootPosition; -} - - -qreal QScrollerPrivate::nextSegmentPosition(QQueue<ScrollSegment> &segments, qint64 now, qreal oldPos) -{ - qreal pos = oldPos; - - // check the X segments for new positions - while (!segments.isEmpty()) { - const ScrollSegment s = segments.head(); - - if ((s.startTime + s.deltaTime * s.stopProgress) <= now) { - segments.dequeue(); - pos = s.stopPos; - } else if (s.startTime <= now) { - qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime); - pos = s.startPos + s.deltaPos * s.curve.valueForProgress(progress); - if (s.deltaPos > 0 ? pos > s.stopPos : pos < s.stopPos) { - segments.dequeue(); - pos = s.stopPos; - } else { - break; - } - } else { - break; - } - } - return pos; -} - -void QScrollerPrivate::setContentPositionHelperScrolling() -{ - qint64 now = monotonicTimer.elapsed(); - QPointF newPos = contentPosition + overshootPosition; - - newPos.setX(nextSegmentPosition(xSegments, now, newPos.x())); - newPos.setY(nextSegmentPosition(ySegments, now, newPos.y())); - - // -- set the position and handle overshoot - qScrollerDebug() << "QScroller::setContentPositionHelperScrolling()"; - qScrollerDebug() << " --> overshoot:" << overshootPosition << "- new pos:" << newPos; - - QPointF newClampedPos = clampToRect(newPos, contentPosRange); - - overshootPosition = newPos - newClampedPos; - contentPosition = newClampedPos; - - QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted : QScrollEvent::ScrollUpdated); - sendEvent(target, &se); - firstScroll = false; - - qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition; -} - -/*! \internal - Returns the next snap point in direction. - If \a direction >0 it will return the next snap point that is larger than the current position. - If \a direction <0 it will return the next snap point that is smaller than the current position. - If \a direction ==0 it will return the nearest snap point (or the current position if we are already - on a snap point. - Returns the nearest snap position or NaN if no such point could be found. - */ -qreal QScrollerPrivate::nextSnapPos(qreal p, int dir, Qt::Orientation orientation) -{ - qreal bestSnapPos = Q_QNAN; - qreal bestSnapPosDist = Q_INFINITY; - - qreal minPos; - qreal maxPos; - - if (orientation == Qt::Horizontal) { - minPos = contentPosRange.left(); - maxPos = contentPosRange.right(); - } else { - minPos = contentPosRange.top(); - maxPos = contentPosRange.bottom(); - } - - if (orientation == Qt::Horizontal) { - // the snap points in the list - foreach (qreal snapPos, snapPositionsX) { - qreal snapPosDist = snapPos - p; - if ((dir > 0 && snapPosDist < 0) || - (dir < 0 && snapPosDist > 0)) - continue; // wrong direction - if (snapPos < minPos || snapPos > maxPos ) - continue; // invalid - - if (qIsNaN(bestSnapPos) || - qAbs(snapPosDist) < bestSnapPosDist ) { - bestSnapPos = snapPos; - bestSnapPosDist = qAbs(snapPosDist); - } - } - - // the snap point interval - if (snapIntervalX > 0.0) { - qreal first = minPos + snapFirstX; - qreal snapPos; - if (dir > 0) - snapPos = qCeil((p - first) / snapIntervalX) * snapIntervalX + first; - else if (dir < 0) - snapPos = qFloor((p - first) / snapIntervalX) * snapIntervalX + first; - else if (p <= first) - snapPos = first; - else - { - qreal last = qFloor((maxPos - first) / snapIntervalX) * snapIntervalX + first; - if (p >= last) - snapPos = last; - else - snapPos = qRound((p - first) / snapIntervalX) * snapIntervalX + first; - } - - if (snapPos >= first && snapPos <= maxPos ) { - qreal snapPosDist = snapPos - p; - - if (qIsNaN(bestSnapPos) || - qAbs(snapPosDist) < bestSnapPosDist ) { - bestSnapPos = snapPos; - bestSnapPosDist = qAbs(snapPosDist); - } - } - } - - } else { // (orientation == Qt::Vertical) - // the snap points in the list - foreach (qreal snapPos, snapPositionsY) { - qreal snapPosDist = snapPos - p; - if ((dir > 0 && snapPosDist < 0) || - (dir < 0 && snapPosDist > 0)) - continue; // wrong direction - if (snapPos < minPos || snapPos > maxPos ) - continue; // invalid - - if (qIsNaN(bestSnapPos) || - qAbs(snapPosDist) < bestSnapPosDist) { - bestSnapPos = snapPos; - bestSnapPosDist = qAbs(snapPosDist); - } - } - - // the snap point interval - if (snapIntervalY > 0.0) { - qreal first = minPos + snapFirstY; - qreal snapPos; - if (dir > 0) - snapPos = qCeil((p - first) / snapIntervalY) * snapIntervalY + first; - else if (dir < 0) - snapPos = qFloor((p - first) / snapIntervalY) * snapIntervalY + first; - else if (p <= first) - snapPos = first; - else - { - qreal last = qFloor((maxPos - first) / snapIntervalY) * snapIntervalY + first; - if (p >= last) - snapPos = last; - else - snapPos = qRound((p - first) / snapIntervalY) * snapIntervalY + first; - } - - if (snapPos >= first && snapPos <= maxPos ) { - qreal snapPosDist = snapPos - p; - - if (qIsNaN(bestSnapPos) || - qAbs(snapPosDist) < bestSnapPosDist) { - bestSnapPos = snapPos; - bestSnapPosDist = qAbs(snapPosDist); - } - } - } - } - - return bestSnapPos; -} - -/*! - \enum QScroller::State - - This enum contains the different QScroller states. - - \value Inactive The scroller is not scrolling and nothing is pressed. - \value Pressed A touch event was received or the mouse button was pressed but the scroll area is currently not dragged. - \value Dragging The scroll area is currently following the touch point or mouse. - \value Scrolling The scroll area is moving on it's own. -*/ - -/*! - \enum QScroller::ScrollerGestureType - - This enum contains the different gesture types that are supported by the QScroller gesture recognizer. - - \value TouchGesture The gesture recognizer will only trigger on touch - events. Specifically it will react on single touch points when using a - touch screen and dual touch points when using a touchpad. - \value LeftMouseButtonGesture The gesture recognizer will only trigger on left mouse button events. - \value MiddleMouseButtonGesture The gesture recognizer will only trigger on middle mouse button events. - \value RightMouseButtonGesture The gesture recognizer will only trigger on right mouse button events. -*/ - -/*! - \enum QScroller::Input - - This enum contains an input device agnostic view of input events that are relevant for QScroller. - - \value InputPress The user pressed the input device (e.g. QEvent::MouseButtonPress, - QEvent::GraphicsSceneMousePress, QEvent::TouchBegin) - - \value InputMove The user moved the input device (e.g. QEvent::MouseMove, - QEvent::GraphicsSceneMouseMove, QEvent::TouchUpdate) - - \value InputRelease The user released the input device (e.g. QEvent::MouseButtonRelease, - QEvent::GraphicsSceneMouseRelease, QEvent::TouchEnd) - -*/ - -QT_END_NAMESPACE diff --git a/src/gui/util/qscroller.h b/src/gui/util/qscroller.h deleted file mode 100644 index 1599c7d..0000000 --- a/src/gui/util/qscroller.h +++ /dev/null @@ -1,155 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSCROLLER_H -#define QSCROLLER_H - -#include <QtCore/QObject> -#include <QtCore/QPointF> -#include <QtGui/QScrollerProperties> - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -class QWidget; -class QScrollerPrivate; -class QScrollerProperties; -#ifndef QT_NO_GESTURES -class QFlickGestureRecognizer; -class QMouseFlickGestureRecognizer; -#endif - -class Q_GUI_EXPORT QScroller : public QObject -{ - Q_OBJECT - Q_PROPERTY(State state READ state NOTIFY stateChanged) - Q_PROPERTY(QScrollerProperties scrollerProperties READ scrollerProperties WRITE setScrollerProperties NOTIFY scrollerPropertiesChanged) - Q_ENUMS(State) - -public: - enum State - { - Inactive, - Pressed, - Dragging, - Scrolling - }; - - enum ScrollerGestureType - { - TouchGesture, - LeftMouseButtonGesture, - RightMouseButtonGesture, - MiddleMouseButtonGesture - }; - - enum Input - { - InputPress = 1, - InputMove, - InputRelease - }; - - static bool hasScroller(QObject *target); - - static QScroller *scroller(QObject *target); - static const QScroller *scroller(const QObject *target); - -#ifndef QT_NO_GESTURES - static Qt::GestureType grabGesture(QObject *target, ScrollerGestureType gestureType = TouchGesture); - static Qt::GestureType grabbedGesture(QObject *target); - static void ungrabGesture(QObject *target); -#endif - - static QList<QScroller *> activeScrollers(); - - QObject *target() const; - - State state() const; - - bool handleInput(Input input, const QPointF &position, qint64 timestamp = 0); - - void stop(); - QPointF velocity() const; - QPointF finalPosition() const; - QPointF pixelPerMeter() const; - - QScrollerProperties scrollerProperties() const; - - void setSnapPositionsX( const QList<qreal> &positions ); - void setSnapPositionsX( qreal first, qreal interval ); - void setSnapPositionsY( const QList<qreal> &positions ); - void setSnapPositionsY( qreal first, qreal interval ); - -public Q_SLOTS: - void setScrollerProperties(const QScrollerProperties &prop); - void scrollTo(const QPointF &pos); - void scrollTo(const QPointF &pos, int scrollTime); - void ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin); - void ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin, int scrollTime); - void resendPrepareEvent(); - -Q_SIGNALS: - void stateChanged(QScroller::State newstate); - void scrollerPropertiesChanged(const QScrollerProperties &); - -private: - QScrollerPrivate *d_ptr; - - QScroller(QObject *target); - virtual ~QScroller(); - - Q_DISABLE_COPY(QScroller) - Q_DECLARE_PRIVATE(QScroller) - -#ifndef QT_NO_GESTURES - friend class QFlickGestureRecognizer; -#endif -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QSCROLLER_H diff --git a/src/gui/util/qscroller_p.h b/src/gui/util/qscroller_p.h deleted file mode 100644 index c119615..0000000 --- a/src/gui/util/qscroller_p.h +++ /dev/null @@ -1,209 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSCROLLER_P_H -#define QSCROLLER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QObject> -#include <QPointer> -#include <QQueue> -#include <QSet> -#include <QEasingCurve> -#include <QElapsedTimer> -#include <QSizeF> -#include <QPointF> -#include <QRectF> -#include <qscroller.h> -#include <qscrollerproperties.h> -#include <private/qscrollerproperties_p.h> -#include <QAbstractAnimation> - -QT_BEGIN_NAMESPACE - -#ifndef QT_NO_GESTURES -class QFlickGestureRecognizer; -#endif - -#ifndef QT_NO_ANIMATION -class QScrollTimer; -#endif -class QScrollerPrivate : public QObject -{ - Q_OBJECT - Q_DECLARE_PUBLIC(QScroller) - -public: - QScrollerPrivate(QScroller *q, QObject *target); - void init(); - - void sendEvent(QObject *o, QEvent *e); - - void setState(QScroller::State s); - - enum ScrollType { - ScrollTypeFlick = 0, - ScrollTypeScrollTo, - ScrollTypeOvershoot - }; - - struct ScrollSegment { - qint64 startTime; - qint64 deltaTime; - qreal startPos; - qreal deltaPos; - QEasingCurve curve; - qreal stopProgress; // whatever is.. - qreal stopPos; // ..reached first - ScrollType type; - }; - - bool pressWhileInactive(const QPointF &position, qint64 timestamp); - bool moveWhilePressed(const QPointF &position, qint64 timestamp); - bool releaseWhilePressed(const QPointF &position, qint64 timestamp); - bool moveWhileDragging(const QPointF &position, qint64 timestamp); - bool releaseWhileDragging(const QPointF &position, qint64 timestamp); - bool pressWhileScrolling(const QPointF &position, qint64 timestamp); - - void timerTick(); - void timerEventWhileDragging(); - void timerEventWhileScrolling(); - - bool prepareScrolling(const QPointF &position); - void handleDrag(const QPointF &position, qint64 timestamp); - - QPointF realDpi(int screen); - QPointF dpi() const; - void setDpi(const QPointF &dpi); - void setDpiFromWidget(QWidget *widget); - - void updateVelocity(const QPointF &deltaPixelRaw, qint64 deltaTime); - void pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, qreal startPos, qreal deltaPos, qreal stopPos, QEasingCurve::Type curve, Qt::Orientation orientation); - void recalcScrollingSegments(bool forceRecalc = false); - qreal scrollingSegmentsEndPos(Qt::Orientation orientation) const; - bool scrollingSegmentsValid(Qt::Orientation orientation); - void createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, Qt::Orientation orientation, ScrollType type); - void createScrollingSegments(qreal v, qreal startPos, qreal ppm, Qt::Orientation orientation); - - void setContentPositionHelperDragging(const QPointF &deltaPos); - void setContentPositionHelperScrolling(); - - qreal nextSnapPos(qreal p, int dir, Qt::Orientation orientation); - static qreal nextSegmentPosition(QQueue<ScrollSegment> &segments, qint64 now, qreal oldPos); - - inline int frameRateSkip() const { return properties.d.data()->frameRate; } - - static const char *stateName(QScroller::State state); - static const char *inputName(QScroller::Input input); - -public slots: - void targetDestroyed(); - -public: - // non static - QObject *target; - QScrollerProperties properties; -#ifndef QT_NO_GESTURES - QFlickGestureRecognizer *recognizer; - Qt::GestureType recognizerType; -#endif - - // scroller state: - - // QPointer<QObject> scrollTarget; - QSizeF viewportSize; - QRectF contentPosRange; - QPointF contentPosition; - QPointF overshootPosition; // the number of pixels we are overshooting (before overshootDragResistanceFactor) - - // state - - bool enabled; - QScroller::State state; - bool firstScroll; // true if we haven't already send a scroll event - - QPointF oldVelocity; // the release velocity of the last drag - - QPointF pressPosition; - QPointF lastPosition; - qint64 pressTimestamp; - qint64 lastTimestamp; - - QPointF dragDistance; // the distance we should move during the next drag timer event - - QQueue<ScrollSegment> xSegments; - QQueue<ScrollSegment> ySegments; - - // snap positions - QList<qreal> snapPositionsX; - qreal snapFirstX; - qreal snapIntervalX; - QList<qreal> snapPositionsY; - qreal snapFirstY; - qreal snapIntervalY; - - QPointF pixelPerMeter; - - QElapsedTimer monotonicTimer; - - QPointF releaseVelocity; // the starting velocity of the scrolling state -#ifndef QT_NO_ANIMATION - QScrollTimer *scrollTimer; -#endif - - QScroller *q_ptr; -}; - - -QT_END_NAMESPACE - -#endif // QSCROLLER_P_H - diff --git a/src/gui/util/qscrollerproperties.cpp b/src/gui/util/qscrollerproperties.cpp deleted file mode 100644 index 85e2e82..0000000 --- a/src/gui/util/qscrollerproperties.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QPointer> -#include <QObject> -#include <QtCore/qmath.h> -#ifdef Q_WS_WIN -# include <QLibrary> -#endif - -#include "qscrollerproperties.h" -#include "private/qscrollerproperties_p.h" - -QT_BEGIN_NAMESPACE - -static QScrollerPropertiesPrivate *userDefaults = 0; -static QScrollerPropertiesPrivate *systemDefaults = 0; - -QScrollerPropertiesPrivate *QScrollerPropertiesPrivate::defaults() -{ - if (!systemDefaults) { - QScrollerPropertiesPrivate spp; - spp.mousePressEventDelay = qreal(0.25); - spp.dragStartDistance = qreal(5.0 / 1000); - spp.dragVelocitySmoothingFactor = qreal(0.8); - spp.axisLockThreshold = qreal(0); - spp.scrollingCurve.setType(QEasingCurve::OutQuad); - spp.decelerationFactor = qreal(0.125); - spp.minimumVelocity = qreal(50.0 / 1000); - spp.maximumVelocity = qreal(500.0 / 1000); - spp.maximumClickThroughVelocity = qreal(66.5 / 1000); - spp.acceleratingFlickMaximumTime = qreal(1.25); - spp.acceleratingFlickSpeedupFactor = qreal(3.0); - spp.snapPositionRatio = qreal(0.5); - spp.snapTime = qreal(0.3); - spp.overshootDragResistanceFactor = qreal(0.5); - spp.overshootDragDistanceFactor = qreal(1); - spp.overshootScrollDistanceFactor = qreal(0.5); - spp.overshootScrollTime = qreal(0.7); -# ifdef Q_WS_WIN - if (QLibrary::resolve(QLatin1String("UxTheme"), "BeginPanningFeedback")) - spp.overshootScrollTime = qreal(0.35); -# endif - spp.hOvershootPolicy = QScrollerProperties::OvershootWhenScrollable; - spp.vOvershootPolicy = QScrollerProperties::OvershootWhenScrollable; - spp.frameRate = QScrollerProperties::Standard; - - systemDefaults = new QScrollerPropertiesPrivate(spp); - } - return new QScrollerPropertiesPrivate(userDefaults ? *userDefaults : *systemDefaults); -} - -/*! - \class QScrollerProperties - \brief The QScrollerProperties class stores the settings for a QScroller. - \since 4.8 - - The QScrollerProperties class stores the parameters used by QScroller. - - The default settings are platform dependent so that Qt emulates the - platform behaviour for kinetic scrolling. - - As a convention the QScrollerProperties are in physical units (meter, - seconds) and are converted by QScroller using the current DPI. - - \sa QScroller -*/ - -/*! - Constructs new scroller properties. -*/ -QScrollerProperties::QScrollerProperties() - : d(QScrollerPropertiesPrivate::defaults()) -{ -} - -/*! - Constructs a copy of \a sp. -*/ -QScrollerProperties::QScrollerProperties(const QScrollerProperties &sp) - : d(new QScrollerPropertiesPrivate(*sp.d)) -{ -} - -/*! - Assigns \a sp to these scroller properties and returns a reference to these scroller properties. -*/ -QScrollerProperties &QScrollerProperties::operator=(const QScrollerProperties &sp) -{ - *d.data() = *sp.d.data(); - return *this; -} - -/*! - Destroys the scroller properties. -*/ -QScrollerProperties::~QScrollerProperties() -{ -} - -/*! - Returns true if these scroller properties are equal to \a sp; otherwise returns false. -*/ -bool QScrollerProperties::operator==(const QScrollerProperties &sp) const -{ - return *d.data() == *sp.d.data(); -} - -/*! - Returns true if these scroller properties are different from \a sp; otherwise returns false. -*/ -bool QScrollerProperties::operator!=(const QScrollerProperties &sp) const -{ - return !(*d.data() == *sp.d.data()); -} - -bool QScrollerPropertiesPrivate::operator==(const QScrollerPropertiesPrivate &p) const -{ - bool same = true; - same &= (mousePressEventDelay == p.mousePressEventDelay); - same &= (dragStartDistance == p.dragStartDistance); - same &= (dragVelocitySmoothingFactor == p.dragVelocitySmoothingFactor); - same &= (axisLockThreshold == p.axisLockThreshold); - same &= (scrollingCurve == p.scrollingCurve); - same &= (decelerationFactor == p.decelerationFactor); - same &= (minimumVelocity == p.minimumVelocity); - same &= (maximumVelocity == p.maximumVelocity); - same &= (maximumClickThroughVelocity == p.maximumClickThroughVelocity); - same &= (acceleratingFlickMaximumTime == p.acceleratingFlickMaximumTime); - same &= (acceleratingFlickSpeedupFactor == p.acceleratingFlickSpeedupFactor); - same &= (snapPositionRatio == p.snapPositionRatio); - same &= (snapTime == p.snapTime); - same &= (overshootDragResistanceFactor == p.overshootDragResistanceFactor); - same &= (overshootDragDistanceFactor == p.overshootDragDistanceFactor); - same &= (overshootScrollDistanceFactor == p.overshootScrollDistanceFactor); - same &= (overshootScrollTime == p.overshootScrollTime); - same &= (hOvershootPolicy == p.hOvershootPolicy); - same &= (vOvershootPolicy == p.vOvershootPolicy); - same &= (frameRate == p.frameRate); - return same; -} - -/*! - Sets the scroller properties for all new QScrollerProperties objects to \a sp. - - Use this function to override the platform default properties returned by the default - constructor. If you only want to change the scroller properties of a single scroller, use - QScroller::setScrollerProperties() - - \note Calling this function will not change the content of already existing - QScrollerProperties objects. - - \sa unsetDefaultScrollerProperties() -*/ -void QScrollerProperties::setDefaultScrollerProperties(const QScrollerProperties &sp) -{ - if (!userDefaults) - userDefaults = new QScrollerPropertiesPrivate(*sp.d); - else - *userDefaults = *sp.d; -} - -/*! - Sets the scroller properties returned by the default constructor back to the platform default - properties. - - \sa setDefaultScrollerProperties() -*/ -void QScrollerProperties::unsetDefaultScrollerProperties() -{ - delete userDefaults; - userDefaults = 0; -} - -/*! - Query the \a metric value of the scroller properties. - - \sa setScrollMetric(), ScrollMetric -*/ -QVariant QScrollerProperties::scrollMetric(ScrollMetric metric) const -{ - switch (metric) { - case MousePressEventDelay: return d->mousePressEventDelay; - case DragStartDistance: return d->dragStartDistance; - case DragVelocitySmoothingFactor: return d->dragVelocitySmoothingFactor; - case AxisLockThreshold: return d->axisLockThreshold; - case ScrollingCurve: return d->scrollingCurve; - case DecelerationFactor: return d->decelerationFactor; - case MinimumVelocity: return d->minimumVelocity; - case MaximumVelocity: return d->maximumVelocity; - case MaximumClickThroughVelocity: return d->maximumClickThroughVelocity; - case AcceleratingFlickMaximumTime: return d->acceleratingFlickMaximumTime; - case AcceleratingFlickSpeedupFactor:return d->acceleratingFlickSpeedupFactor; - case SnapPositionRatio: return d->snapPositionRatio; - case SnapTime: return d->snapTime; - case OvershootDragResistanceFactor: return d->overshootDragResistanceFactor; - case OvershootDragDistanceFactor: return d->overshootDragDistanceFactor; - case OvershootScrollDistanceFactor: return d->overshootScrollDistanceFactor; - case OvershootScrollTime: return d->overshootScrollTime; - case HorizontalOvershootPolicy: return QVariant::fromValue(d->hOvershootPolicy); - case VerticalOvershootPolicy: return QVariant::fromValue(d->vOvershootPolicy); - case FrameRate: return QVariant::fromValue(d->frameRate); - case ScrollMetricCount: break; - } - return QVariant(); -} - -/*! - Set a specific value of the \a metric ScrollerMetric to \a value. - - \sa scrollMetric(), ScrollMetric -*/ -void QScrollerProperties::setScrollMetric(ScrollMetric metric, const QVariant &value) -{ - switch (metric) { - case MousePressEventDelay: d->mousePressEventDelay = value.toReal(); break; - case DragStartDistance: d->dragStartDistance = value.toReal(); break; - case DragVelocitySmoothingFactor: d->dragVelocitySmoothingFactor = qBound(qreal(0), value.toReal(), qreal(1)); break; - case AxisLockThreshold: d->axisLockThreshold = qBound(qreal(0), value.toReal(), qreal(1)); break; - case ScrollingCurve: d->scrollingCurve = value.toEasingCurve(); break; - case DecelerationFactor: d->decelerationFactor = value.toReal(); break; - case MinimumVelocity: d->minimumVelocity = value.toReal(); break; - case MaximumVelocity: d->maximumVelocity = value.toReal(); break; - case MaximumClickThroughVelocity: d->maximumClickThroughVelocity = value.toReal(); break; - case AcceleratingFlickMaximumTime: d->acceleratingFlickMaximumTime = value.toReal(); break; - case AcceleratingFlickSpeedupFactor:d->acceleratingFlickSpeedupFactor = value.toReal(); break; - case SnapPositionRatio: d->snapPositionRatio = qBound(qreal(0), value.toReal(), qreal(1)); break; - case SnapTime: d->snapTime = value.toReal(); break; - case OvershootDragResistanceFactor: d->overshootDragResistanceFactor = value.toReal(); break; - case OvershootDragDistanceFactor: d->overshootDragDistanceFactor = qBound(qreal(0), value.toReal(), qreal(1)); break; - case OvershootScrollDistanceFactor: d->overshootScrollDistanceFactor = qBound(qreal(0), value.toReal(), qreal(1)); break; - case OvershootScrollTime: d->overshootScrollTime = value.toReal(); break; - case HorizontalOvershootPolicy: d->hOvershootPolicy = value.value<QScrollerProperties::OvershootPolicy>(); break; - case VerticalOvershootPolicy: d->vOvershootPolicy = value.value<QScrollerProperties::OvershootPolicy>(); break; - case FrameRate: d->frameRate = value.value<QScrollerProperties::FrameRates>(); break; - case ScrollMetricCount: break; - } -} - -/*! - \enum QScrollerProperties::FrameRates - - This enum describes the available frame rates used while dragging or scrolling. - - \value Fps60 60 frames per second - \value Fps30 30 frames per second - \value Fps20 20 frames per second - \value Standard the default value is 60 frames per second (which corresponds to QAbstractAnimation). -*/ - -/*! - \enum QScrollerProperties::OvershootPolicy - - This enum describes the various modes of overshooting. - - \value OvershootWhenScrollable Overshooting is possible when the content is scrollable. This is the - default. - - \value OvershootAlwaysOff Overshooting is never enabled, even when the content is scrollable. - - \value OvershootAlwaysOn Overshooting is always enabled, even when the content is not - scrollable. -*/ - -/*! - \enum QScrollerProperties::ScrollMetric - - This enum contains the different scroll metric types. When not indicated otherwise the - setScrollMetric function expects a QVariant of type qreal. - - See the QScroller documentation for further details of the concepts behind the different - values. - - \value MousePressEventDelay This is the time a mouse press event is delayed when starting - a flick gesture in \c{[s]}. If the gesture is triggered within that time, no mouse press or - release is sent to the scrolled object. If it triggers after that delay the delayed - mouse press plus a faked release event at global postion \c{QPoint(-QWIDGETSIZE_MAX, - -QWIDGETSIZE_MAX)} is sent. If the gesture is canceled, then both the delayed mouse - press plus the real release event are delivered. - - \value DragStartDistance This is the minimum distance the touch or mouse point needs to be - moved before the flick gesture is triggered in \c m. - - \value DragVelocitySmoothingFactor A value that describes to which extent new drag velocities are - included in the final scrolling velocity. This value should be in the range between \c 0 and - \c 1. The lower the value, the more smoothing is applied to the dragging velocity. - - \value AxisLockThreshold Restricts the movement to one axis if the movement is inside an angle - around the axis. The threshold must be in the range \c 0 to \c 1. - - \value ScrollingCurve The QEasingCurve used when decelerating the scrolling velocity after an - user initiated flick. Please note that this is the easing curve for the positions, \bold{not} - the velocity: the default is QEasingCurve::OutQuad, which results in a linear decrease in - velocity (1st derivative) and a constant deceleration (2nd derivative). - - \value DecelerationFactor This factor influences how long it takes the scroller to decelerate - to 0 velocity. The actual value depends on the chosen ScrollingCurve. For most - types the value should be in the range from \c 0.1 to \c 2.0 - - \value MinimumVelocity The minimum velocity that is needed after ending the touch or releasing - the mouse to start scrolling in \c{m/s}. - - \value MaximumVelocity This is the maximum velocity that can be reached in \c{m/s}. - - \value MaximumClickThroughVelocity This is the maximum allowed scroll speed for a click-through - in \c{m/s}. This means that a click on a currently (slowly) scrolling object will not only stop - the scrolling but the click event will also be delivered to the UI control. This is - useful when using exponential-type scrolling curves. - - \value AcceleratingFlickMaximumTime This is the maximum time in \c seconds that a flick gesture - can take to be recognized as an accelerating flick. If set to zero no such gesture is - detected. An "accelerating flick" is a flick gesture executed on an already scrolling object. - In such cases the scrolling speed is multiplied by AcceleratingFlickSpeedupFactor in order to - accelerate it. - - \value AcceleratingFlickSpeedupFactor The current speed is multiplied by this number if an - accelerating flick is detected. Should be \c{>= 1}. - - \value SnapPositionRatio This is the distance that the user must drag the area beween two snap - points in order to snap it to the next position. \c{0.33} means that the scroll must only - reach one third of the distance between two snap points to snap to the next one. The ratio must - be between \c 0 and \c 1. - - \value SnapTime This is the time factor for the scrolling curve. A lower value means that the - scrolling will take longer. The scrolling distance is independet of this value. - - \value OvershootDragResistanceFactor This value is the factor between the mouse dragging and - the actual scroll area movement (during overshoot). The factor must be between \c 0 and \c 1. - - \value OvershootDragDistanceFactor This is the maximum distance for overshoot movements while - dragging. The actual overshoot distance is calculated by multiplying this value with the - viewport size of the scrolled object. The factor must be between \c 0 and \c 1. - - \value OvershootScrollDistanceFactor This is the maximum distance for overshoot movements while - scrolling. The actual overshoot distance is calculated by multiplying this value with the - viewport size of the scrolled object. The factor must be between \c 0 and \c 1. - - \value OvershootScrollTime This is the time in \c seconds that is used to play the - complete overshoot animation. - - \value HorizontalOvershootPolicy This is the horizontal overshooting policy (see OvershootPolicy). - - \value VerticalOvershootPolicy This is the horizontal overshooting policy (see OvershootPolicy). - - \value FrameRate This is the frame rate which should be used while dragging or scrolling. - QScroller uses a QAbstractAnimation timer internally to sync all scrolling operations to other - animations that might be active at the same time. If the standard value of 60 frames per - second is too fast, it can be lowered with this setting, - while still being in-sync with QAbstractAnimation. Please note that only the values of the - FrameRates enum are allowed here. - - \value ScrollMetricCount This is always the last entry. -*/ - -QT_END_NAMESPACE diff --git a/src/gui/util/qscrollerproperties.h b/src/gui/util/qscrollerproperties.h deleted file mode 100644 index 75d8932..0000000 --- a/src/gui/util/qscrollerproperties.h +++ /dev/null @@ -1,140 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSCROLLERPROPERTIES_H -#define QSCROLLERPROPERTIES_H - -#include <QtCore/QScopedPointer> -#include <QtCore/QMetaType> -#include <QtCore/QVariant> - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -class QScroller; -class QScrollerPrivate; -class QScrollerPropertiesPrivate; - -class Q_GUI_EXPORT QScrollerProperties -{ -public: - QScrollerProperties(); - QScrollerProperties(const QScrollerProperties &sp); - QScrollerProperties &operator=(const QScrollerProperties &sp); - virtual ~QScrollerProperties(); - - bool operator==(const QScrollerProperties &sp) const; - bool operator!=(const QScrollerProperties &sp) const; - - static void setDefaultScrollerProperties(const QScrollerProperties &sp); - static void unsetDefaultScrollerProperties(); - - enum OvershootPolicy - { - OvershootWhenScrollable, - OvershootAlwaysOff, - OvershootAlwaysOn - }; - - enum FrameRates { - Standard, - Fps60, - Fps30, - Fps20 - }; - - enum ScrollMetric - { - MousePressEventDelay, // qreal [s] - DragStartDistance, // qreal [m] - DragVelocitySmoothingFactor, // qreal [0..1/s] (complex calculation involving time) v = v_new* DASF + v_old * (1-DASF) - AxisLockThreshold, // qreal [0..1] atan(|min(dx,dy)|/|max(dx,dy)|) - - ScrollingCurve, // QEasingCurve - DecelerationFactor, // slope of the curve - - MinimumVelocity, // qreal [m/s] - MaximumVelocity, // qreal [m/s] - MaximumClickThroughVelocity, // qreal [m/s] - - AcceleratingFlickMaximumTime, // qreal [s] - AcceleratingFlickSpeedupFactor, // qreal [1..] - - SnapPositionRatio, // qreal [0..1] - SnapTime, // qreal [s] - - OvershootDragResistanceFactor, // qreal [0..1] - OvershootDragDistanceFactor, // qreal [0..1] - OvershootScrollDistanceFactor, // qreal [0..1] - OvershootScrollTime, // qreal [s] - - HorizontalOvershootPolicy, // enum OvershootPolicy - VerticalOvershootPolicy, // enum OvershootPolicy - FrameRate, // enum FrameRates - - ScrollMetricCount - }; - - QVariant scrollMetric(ScrollMetric metric) const; - void setScrollMetric(ScrollMetric metric, const QVariant &value); - -protected: - QScopedPointer<QScrollerPropertiesPrivate> d; - -private: - QScrollerProperties(QScrollerPropertiesPrivate &dd); - - friend class QScrollerPropertiesPrivate; - friend class QScroller; - friend class QScrollerPrivate; -}; - -QT_END_NAMESPACE - -Q_DECLARE_METATYPE(QScrollerProperties::OvershootPolicy) -Q_DECLARE_METATYPE(QScrollerProperties::FrameRates) - -QT_END_HEADER - -#endif // QSCROLLERPROPERTIES_H diff --git a/src/gui/util/qundogroup.cpp b/src/gui/util/qundogroup.cpp index 42cda74..a24ce8d 100644 --- a/src/gui/util/qundogroup.cpp +++ b/src/gui/util/qundogroup.cpp @@ -375,15 +375,18 @@ bool QUndoGroup::isClean() const for undo, if the group is empty or if none of the stacks are active, this action will be disabled. - If \a prefix is empty, the default prefix "Undo" is used. + If \a prefix is empty, the default template "Undo %1" is used instead of prefix. + Before Qt 4.8, the prefix "Undo" was used by default. \sa createRedoAction() canUndo() QUndoCommand::text() */ QAction *QUndoGroup::createUndoAction(QObject *parent, const QString &prefix) const { - QString pref = prefix.isEmpty() ? tr("Undo") : prefix; - QUndoAction *result = new QUndoAction(pref, parent); + QUndoAction *result = new QUndoAction(prefix, parent); + if (prefix.isEmpty()) + result->setTextFormat(tr("Undo %1"), tr("Undo", "Default text for undo action")); + result->setEnabled(canUndo()); result->setPrefixedText(undoText()); connect(this, SIGNAL(canUndoChanged(bool)), @@ -403,15 +406,18 @@ QAction *QUndoGroup::createUndoAction(QObject *parent, const QString &prefix) co for redo, if the group is empty or if none of the stacks are active, this action will be disabled. - If \a prefix is empty, the default prefix "Undo" is used. + If \a prefix is empty, the default template "Redo %1" is used instead of prefix. + Before Qt 4.8, the prefix "Redo" was used by default. \sa createUndoAction() canRedo() QUndoCommand::text() */ QAction *QUndoGroup::createRedoAction(QObject *parent, const QString &prefix) const { - QString pref = prefix.isEmpty() ? tr("Redo") : prefix; - QUndoAction *result = new QUndoAction(pref, parent); + QUndoAction *result = new QUndoAction(prefix, parent); + if (prefix.isEmpty()) + result->setTextFormat(tr("Redo %1"), tr("Redo", "Default text for redo action")); + result->setEnabled(canRedo()); result->setPrefixedText(redoText()); connect(this, SIGNAL(canRedoChanged(bool)), diff --git a/src/gui/util/qundostack.cpp b/src/gui/util/qundostack.cpp index 6b038ee..1dfab5d 100644 --- a/src/gui/util/qundostack.cpp +++ b/src/gui/util/qundostack.cpp @@ -114,7 +114,7 @@ QUndoCommand::QUndoCommand(const QString &text, QUndoCommand *parent) d = new QUndoCommandPrivate; if (parent != 0) parent->d->child_list.append(this); - d->text = text; + setText(text); } /*! @@ -230,10 +230,9 @@ void QUndoCommand::undo() Returns a short text string describing what this command does; for example, "insert text". - The text is used when the text properties of the stack's undo and redo - actions are updated. + The text is used for names of items in QUndoView. - \sa setText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction() + \sa actionText(), setText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction() */ QString QUndoCommand::text() const @@ -242,17 +241,47 @@ QString QUndoCommand::text() const } /*! + \since 4.8 + + Returns a short text string describing what this command does; for example, + "insert text". + + The text is used when the text properties of the stack's undo and redo + actions are updated. + + \sa text(), setText(), QUndoStack::createUndoAction(), QUndoStack::createRedoAction() +*/ + +QString QUndoCommand::actionText() const +{ + return d->actionText; +} + +/*! Sets the command's text to be the \a text specified. The specified text should be a short user-readable string describing what this command does. - \sa text() QUndoStack::createUndoAction() QUndoStack::createRedoAction() + If you need to have two different strings for text() and actionText(), separate + them with "\n" and pass into this function. Even if you do not use this feature + for English strings during development, you can still let translators use two + different strings in order to match specific languages' needs. + The described feature and the function actionText() are available since Qt 4.8. + + \sa text() actionText() QUndoStack::createUndoAction() QUndoStack::createRedoAction() */ void QUndoCommand::setText(const QString &text) { - d->text = text; + int cdpos = text.indexOf(QLatin1Char('\n')); + if (cdpos > 0) { + d->text = text.left(cdpos); + d->actionText = text.mid(cdpos + 1); + } else { + d->text = text; + d->actionText = text; + } } /*! @@ -374,11 +403,24 @@ QUndoAction::QUndoAction(const QString &prefix, QObject *parent) void QUndoAction::setPrefixedText(const QString &text) { - QString s = m_prefix; - if (!m_prefix.isEmpty() && !text.isEmpty()) - s.append(QLatin1Char(' ')); - s.append(text); - setText(s); + if (m_defaultText.isEmpty()) { + QString s = m_prefix; + if (!m_prefix.isEmpty() && !text.isEmpty()) + s.append(QLatin1Char(' ')); + s.append(text); + setText(s); + } else { + if (text.isEmpty()) + setText(m_defaultText); + else + setText(m_prefix.arg(text)); + } +} + +void QUndoAction::setTextFormat(const QString &textFormat, const QString &defaultText) +{ + m_prefix = textFormat; + m_defaultText = defaultText; } #endif // QT_NO_ACTION @@ -783,7 +825,7 @@ bool QUndoStack::canRedo() const /*! Returns the text of the command which will be undone in the next call to undo(). - \sa QUndoCommand::text() redoText() + \sa QUndoCommand::actionText() redoText() */ QString QUndoStack::undoText() const @@ -792,14 +834,14 @@ QString QUndoStack::undoText() const if (!d->macro_stack.isEmpty()) return QString(); if (d->index > 0) - return d->command_list.at(d->index - 1)->text(); + return d->command_list.at(d->index - 1)->actionText(); return QString(); } /*! Returns the text of the command which will be redone in the next call to redo(). - \sa QUndoCommand::text() undoText() + \sa QUndoCommand::actionText() undoText() */ QString QUndoStack::redoText() const @@ -808,7 +850,7 @@ QString QUndoStack::redoText() const if (!d->macro_stack.isEmpty()) return QString(); if (d->index < d->command_list.size()) - return d->command_list.at(d->index)->text(); + return d->command_list.at(d->index)->actionText(); return QString(); } @@ -822,15 +864,18 @@ QString QUndoStack::redoText() const prefixed by the specified \a prefix. If there is no command available for undo, this action will be disabled. - If \a prefix is empty, the default prefix "Undo" is used. + If \a prefix is empty, the default template "Undo %1" is used instead of prefix. + Before Qt 4.8, the prefix "Undo" was used by default. \sa createRedoAction(), canUndo(), QUndoCommand::text() */ QAction *QUndoStack::createUndoAction(QObject *parent, const QString &prefix) const { - QString pref = prefix.isEmpty() ? tr("Undo") : prefix; - QUndoAction *result = new QUndoAction(pref, parent); + QUndoAction *result = new QUndoAction(prefix, parent); + if (prefix.isEmpty()) + result->setTextFormat(tr("Undo %1"), tr("Undo", "Default text for undo action")); + result->setEnabled(canUndo()); result->setPrefixedText(undoText()); connect(this, SIGNAL(canUndoChanged(bool)), @@ -849,15 +894,18 @@ QAction *QUndoStack::createUndoAction(QObject *parent, const QString &prefix) co prefixed by the specified \a prefix. If there is no command available for redo, this action will be disabled. - If \a prefix is empty, the default prefix "Redo" is used. + If \a prefix is empty, the default template "Redo %1" is used instead of prefix. + Before Qt 4.8, the prefix "Redo" was used by default. \sa createUndoAction(), canRedo(), QUndoCommand::text() */ QAction *QUndoStack::createRedoAction(QObject *parent, const QString &prefix) const { - QString pref = prefix.isEmpty() ? tr("Redo") : prefix; - QUndoAction *result = new QUndoAction(pref, parent); + QUndoAction *result = new QUndoAction(prefix, parent); + if (prefix.isEmpty()) + result->setTextFormat(tr("Redo %1"), tr("Redo", "Default text for redo action")); + result->setEnabled(canRedo()); result->setPrefixedText(redoText()); connect(this, SIGNAL(canRedoChanged(bool)), diff --git a/src/gui/util/qundostack.h b/src/gui/util/qundostack.h index 65941b5..700996f 100644 --- a/src/gui/util/qundostack.h +++ b/src/gui/util/qundostack.h @@ -70,6 +70,7 @@ public: virtual void redo(); QString text() const; + QString actionText() const; void setText(const QString &text); virtual int id() const; diff --git a/src/gui/util/qundostack_p.h b/src/gui/util/qundostack_p.h index 3c7d0e7..a100763 100644 --- a/src/gui/util/qundostack_p.h +++ b/src/gui/util/qundostack_p.h @@ -70,6 +70,7 @@ public: QUndoCommandPrivate() : id(-1) {} QList<QUndoCommand*> child_list; QString text; + QString actionText; int id; }; @@ -98,10 +99,12 @@ class QUndoAction : public QAction Q_OBJECT public: QUndoAction(const QString &prefix, QObject *parent = 0); + void setTextFormat(const QString &textFormat, const QString &defaultText); public Q_SLOTS: void setPrefixedText(const QString &text); private: QString m_prefix; + QString m_defaultText; }; #endif // QT_NO_ACTION diff --git a/src/gui/util/util.pri b/src/gui/util/util.pri index 2814a2d..f125f82 100644 --- a/src/gui/util/util.pri +++ b/src/gui/util/util.pri @@ -6,11 +6,6 @@ HEADERS += \ util/qcompleter_p.h \ util/qdesktopservices.h \ util/qsystemtrayicon_p.h \ - util/qscroller.h \ - util/qscroller_p.h \ - util/qscrollerproperties.h \ - util/qscrollerproperties_p.h \ - util/qflickgesture_p.h \ util/qundogroup.h \ util/qundostack.h \ util/qundostack_p.h \ @@ -20,9 +15,6 @@ SOURCES += \ util/qsystemtrayicon.cpp \ util/qcompleter.cpp \ util/qdesktopservices.cpp \ - util/qscroller.cpp \ - util/qscrollerproperties.cpp \ - util/qflickgesture.cpp \ util/qundogroup.cpp \ util/qundostack.cpp \ util/qundoview.cpp @@ -65,7 +57,3 @@ symbian { DEFINES += USE_SCHEMEHANDLER } } - -macx { - OBJECTIVE_SOURCES += util/qscroller_mac.mm -} diff --git a/src/gui/widgets/qabstractscrollarea.cpp b/src/gui/widgets/qabstractscrollarea.cpp index dabfec0..2503b99 100644 --- a/src/gui/widgets/qabstractscrollarea.cpp +++ b/src/gui/widgets/qabstractscrollarea.cpp @@ -53,8 +53,6 @@ #include "qpainter.h" #include "qmargins.h" -#include <QDebug> - #include "qabstractscrollarea_p.h" #include <qwidget.h> @@ -64,10 +62,6 @@ #include <private/qt_mac_p.h> #include <private/qt_cocoa_helpers_mac_p.h> #endif -#ifdef Q_WS_WIN -# include <qlibrary.h> -# include <windows.h> -#endif QT_BEGIN_NAMESPACE @@ -301,14 +295,9 @@ void QAbstractScrollAreaPrivate::init() q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); layoutChildren(); #ifndef Q_WS_MAC -# ifndef QT_NO_GESTURES +#ifndef QT_NO_GESTURES viewport->grabGesture(Qt::PanGesture); -# endif #endif -#ifdef Q_WS_MAEMO_5 -# ifndef QT_NO_GESTURES - // viewport->grabGesture(Qt::TouchFlickGesture); -# endif #endif } @@ -563,11 +552,6 @@ void QAbstractScrollArea::setViewport(QWidget *widget) d->viewport->grabGesture(Qt::PanGesture); #endif #endif -#ifdef Q_WS_MAEMO_5 -#ifndef QT_NO_GESTURES -// d->viewport->grabGesture(Qt::TouchFlickGesture); -#endif -#endif d->layoutChildren(); if (isVisible()) d->viewport->show(); @@ -1002,66 +986,6 @@ bool QAbstractScrollArea::event(QEvent *e) return false; } #endif // QT_NO_GESTURES - case QEvent::ScrollPrepare: - { - QScrollPrepareEvent *se = static_cast<QScrollPrepareEvent *>(e); - if (d->canStartScrollingAt(se->startPos().toPoint())) { - QScrollBar *hBar = horizontalScrollBar(); - QScrollBar *vBar = verticalScrollBar(); - - se->setViewportSize(QSizeF(viewport()->size())); - se->setContentPosRange(QRectF(0, 0, hBar->maximum(), vBar->maximum())); - se->setContentPos(QPointF(hBar->value(), vBar->value())); - se->accept(); - return true; - } - return false; - } - case QEvent::Scroll: - { - QScrollEvent *se = static_cast<QScrollEvent *>(e); - - QScrollBar *hBar = horizontalScrollBar(); - QScrollBar *vBar = verticalScrollBar(); - hBar->setValue(se->contentPos().x()); - vBar->setValue(se->contentPos().y()); - -#ifdef Q_WS_WIN - typedef BOOL (*PtrBeginPanningFeedback)(HWND); - typedef BOOL (*PtrUpdatePanningFeedback)(HWND, LONG, LONG, BOOL); - typedef BOOL (*PtrEndPanningFeedback)(HWND, BOOL); - - static PtrBeginPanningFeedback ptrBeginPanningFeedback = 0; - static PtrUpdatePanningFeedback ptrUpdatePanningFeedback = 0; - static PtrEndPanningFeedback ptrEndPanningFeedback = 0; - - if (!ptrBeginPanningFeedback) - ptrBeginPanningFeedback = (PtrBeginPanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "BeginPanningFeedback"); - if (!ptrUpdatePanningFeedback) - ptrUpdatePanningFeedback = (PtrUpdatePanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "UpdatePanningFeedback"); - if (!ptrEndPanningFeedback) - ptrEndPanningFeedback = (PtrEndPanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "EndPanningFeedback"); - - if (ptrBeginPanningFeedback && ptrUpdatePanningFeedback && ptrEndPanningFeedback) { - WId wid = window()->winId(); - - if (!se->overshootDistance().isNull() && d->overshoot.isNull()) - ptrBeginPanningFeedback(wid); - if (!se->overshootDistance().isNull()) - ptrUpdatePanningFeedback(wid, -se->overshootDistance().x(), -se->overshootDistance().y(), false); - if (se->overshootDistance().isNull() && !d->overshoot.isNull()) - ptrEndPanningFeedback(wid, true); - } else -#endif - { - QPoint delta = d->overshoot - se->overshootDistance().toPoint(); - if (!delta.isNull()) - viewport()->move(viewport()->pos() + delta); - } - d->overshoot = se->overshootDistance().toPoint(); - - return true; - } case QEvent::StyleChange: case QEvent::LayoutDirectionChange: case QEvent::ApplicationLayoutDirectionChange: @@ -1123,9 +1047,6 @@ bool QAbstractScrollArea::viewportEvent(QEvent *e) case QEvent::GestureOverride: return event(e); #endif - case QEvent::ScrollPrepare: - case QEvent::Scroll: - return event(e); default: break; } @@ -1382,32 +1303,6 @@ void QAbstractScrollArea::scrollContentsBy(int, int) viewport()->update(); } -bool QAbstractScrollAreaPrivate::canStartScrollingAt( const QPoint &startPos ) -{ - Q_Q(QAbstractScrollArea); - -#ifndef QT_NO_GRAPHICSVIEW - // don't start scrolling when a drag mode has been set. - // don't start scrolling on a movable item. - if (QGraphicsView *view = qobject_cast<QGraphicsView *>(q)) { - if (view->dragMode() != QGraphicsView::NoDrag) - return false; - - QGraphicsItem *childItem = view->itemAt(startPos); - - if (childItem && (childItem->flags() & QGraphicsItem::ItemIsMovable)) - return false; - } -#endif - - // don't start scrolling on a QAbstractSlider - if (qobject_cast<QAbstractSlider *>(q->viewport()->childAt(startPos))) { - return false; - } - - return true; -} - void QAbstractScrollAreaPrivate::_q_hslide(int x) { Q_Q(QAbstractScrollArea); diff --git a/src/gui/widgets/qabstractscrollarea_p.h b/src/gui/widgets/qabstractscrollarea_p.h index 76e1c34..85536e3 100644 --- a/src/gui/widgets/qabstractscrollarea_p.h +++ b/src/gui/widgets/qabstractscrollarea_p.h @@ -84,13 +84,11 @@ public: int left, top, right, bottom; // viewport margin int xoffset, yoffset; - QPoint overshoot; void init(); void layoutChildren(); // ### Fix for 4.4, talk to Bjoern E or Girish. virtual void scrollBarPolicyChanged(Qt::Orientation, Qt::ScrollBarPolicy) {} - bool canStartScrollingAt( const QPoint &startPos ); void _q_hslide(int); void _q_vslide(int); diff --git a/src/gui/widgets/qdatetimeedit.cpp b/src/gui/widgets/qdatetimeedit.cpp index 6337113..a4739a7 100644 --- a/src/gui/widgets/qdatetimeedit.cpp +++ b/src/gui/widgets/qdatetimeedit.cpp @@ -2538,20 +2538,32 @@ void QDateTimeEditPrivate::syncCalendarWidget() } QCalendarPopup::QCalendarPopup(QWidget * parent, QCalendarWidget *cw) - : QWidget(parent, Qt::Popup), calendar(0) + : QWidget(parent, Qt::Popup) { setAttribute(Qt::WA_WindowPropagation); dateChanged = false; if (!cw) { - cw = new QCalendarWidget(this); + verifyCalendarInstance(); + } else { + setCalendarWidget(cw); + } +} + +QCalendarWidget *QCalendarPopup::verifyCalendarInstance() +{ + if (calendar.isNull()) { + QCalendarWidget *cw = new QCalendarWidget(this); cw->setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader); #ifdef QT_KEYPAD_NAVIGATION if (QApplication::keypadNavigationEnabled()) cw->setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames); #endif + setCalendarWidget(cw); + return cw; + } else { + return calendar.data(); } - setCalendarWidget(cw); } void QCalendarPopup::setCalendarWidget(QCalendarWidget *cw) @@ -2563,28 +2575,29 @@ void QCalendarPopup::setCalendarWidget(QCalendarWidget *cw) widgetLayout->setMargin(0); widgetLayout->setSpacing(0); } - delete calendar; - calendar = cw; - widgetLayout->addWidget(calendar); + delete calendar.data(); + calendar = QWeakPointer<QCalendarWidget>(cw); + widgetLayout->addWidget(cw); - connect(calendar, SIGNAL(activated(QDate)), this, SLOT(dateSelected(QDate))); - connect(calendar, SIGNAL(clicked(QDate)), this, SLOT(dateSelected(QDate))); - connect(calendar, SIGNAL(selectionChanged()), this, SLOT(dateSelectionChanged())); + connect(cw, SIGNAL(activated(QDate)), this, SLOT(dateSelected(QDate))); + connect(cw, SIGNAL(clicked(QDate)), this, SLOT(dateSelected(QDate))); + connect(cw, SIGNAL(selectionChanged()), this, SLOT(dateSelectionChanged())); - calendar->setFocus(); + cw->setFocus(); } void QCalendarPopup::setDate(const QDate &date) { oldDate = date; - calendar->setSelectedDate(date); + verifyCalendarInstance()->setSelectedDate(date); } void QCalendarPopup::setDateRange(const QDate &min, const QDate &max) { - calendar->setMinimumDate(min); - calendar->setMaximumDate(max); + QCalendarWidget *cw = verifyCalendarInstance(); + cw->setMinimumDate(min); + cw->setMaximumDate(max); } void QCalendarPopup::mousePressEvent(QMouseEvent *event) @@ -2620,7 +2633,7 @@ bool QCalendarPopup::event(QEvent *event) void QCalendarPopup::dateSelectionChanged() { dateChanged = true; - emit newDateSelected(calendar->selectedDate()); + emit newDateSelected(verifyCalendarInstance()->selectedDate()); } void QCalendarPopup::dateSelected(const QDate &date) { diff --git a/src/gui/widgets/qdatetimeedit_p.h b/src/gui/widgets/qdatetimeedit_p.h index acdc878..c85c0fb 100644 --- a/src/gui/widgets/qdatetimeedit_p.h +++ b/src/gui/widgets/qdatetimeedit_p.h @@ -148,11 +148,11 @@ class QCalendarPopup : public QWidget Q_OBJECT public: QCalendarPopup(QWidget *parent = 0, QCalendarWidget *cw = 0); - QDate selectedDate() { return calendar->selectedDate(); } + QDate selectedDate() { return verifyCalendarInstance()->selectedDate(); } void setDate(const QDate &date); void setDateRange(const QDate &min, const QDate &max); - void setFirstDayOfWeek(Qt::DayOfWeek dow) { calendar->setFirstDayOfWeek(dow); } - QCalendarWidget *calendarWidget() const { return calendar; } + void setFirstDayOfWeek(Qt::DayOfWeek dow) { verifyCalendarInstance()->setFirstDayOfWeek(dow); } + QCalendarWidget *calendarWidget() const { return const_cast<QCalendarPopup*>(this)->verifyCalendarInstance(); } void setCalendarWidget(QCalendarWidget *cw); Q_SIGNALS: void activated(const QDate &date); @@ -171,7 +171,9 @@ protected: bool event(QEvent *e); private: - QCalendarWidget *calendar; + QCalendarWidget *verifyCalendarInstance(); + + QWeakPointer<QCalendarWidget> calendar; QDate oldDate; bool dateChanged; }; diff --git a/src/gui/widgets/qdockarealayout.cpp b/src/gui/widgets/qdockarealayout.cpp index 223421d..28c0388 100644 --- a/src/gui/widgets/qdockarealayout.cpp +++ b/src/gui/widgets/qdockarealayout.cpp @@ -2100,7 +2100,6 @@ bool QDockAreaLayoutInfo::updateTabBar() const bool gap = false; int tab_idx = 0; - bool changed = false; for (int i = 0; i < item_list.count(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) @@ -2121,7 +2120,6 @@ bool QDockAreaLayoutInfo::updateTabBar() const tabBar->setTabToolTip(tab_idx, title); #endif tabBar->setTabData(tab_idx, id); - changed = true; } else if (qvariant_cast<quintptr>(tabBar->tabData(tab_idx)) != id) { if (tab_idx + 1 < tabBar->count() && qvariant_cast<quintptr>(tabBar->tabData(tab_idx + 1)) == id) @@ -2133,7 +2131,6 @@ bool QDockAreaLayoutInfo::updateTabBar() const #endif tabBar->setTabData(tab_idx, id); } - changed = true; } if (title != tabBar->tabText(tab_idx)) { @@ -2141,7 +2138,6 @@ bool QDockAreaLayoutInfo::updateTabBar() const #ifndef QT_NO_TOOLTIP tabBar->setTabToolTip(tab_idx, title); #endif - changed = true; } ++tab_idx; @@ -2149,7 +2145,6 @@ bool QDockAreaLayoutInfo::updateTabBar() const while (tab_idx < tabBar->count()) { tabBar->removeTab(tab_idx); - changed = true; } tabBar->blockSignals(blocked); diff --git a/src/gui/widgets/qdockwidget.cpp b/src/gui/widgets/qdockwidget.cpp index 9d1a737..16b60c8 100644 --- a/src/gui/widgets/qdockwidget.cpp +++ b/src/gui/widgets/qdockwidget.cpp @@ -161,7 +161,6 @@ void QDockWidgetTitleButton::paintEvent(QPaintEvent *) { QPainter p(this); - QRect r = rect(); QStyleOptionToolButton opt; opt.init(this); opt.state |= QStyle::State_AutoRaise; diff --git a/src/gui/widgets/qlinecontrol.cpp b/src/gui/widgets/qlinecontrol.cpp index ced66e5..c9dae77 100644 --- a/src/gui/widgets/qlinecontrol.cpp +++ b/src/gui/widgets/qlinecontrol.cpp @@ -435,6 +435,8 @@ void QLineControl::processInputMethodEvent(QInputMethodEvent *event) c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength()); m_cursor += event->replacementStart(); + if (m_cursor < 0) + m_cursor = 0; // insert commit string if (event->replacementLength()) { @@ -447,7 +449,7 @@ void QLineControl::processInputMethodEvent(QInputMethodEvent *event) cursorPositionChanged = true; } - m_cursor = qMin(c, m_text.length()); + m_cursor = qBound(0, c, m_text.length()); for (int i = 0; i < event->attributes().size(); ++i) { const QInputMethodEvent::Attribute &a = event->attributes().at(i); @@ -1593,6 +1595,7 @@ void QLineControl::processKeyEvent(QKeyEvent* event) } bool unknown = false; + bool visual = cursorMoveStyle() == Qt::VisualMoveStyle; if (false) { } @@ -1657,11 +1660,11 @@ void QLineControl::processKeyEvent(QKeyEvent* event) #endif moveCursor(selectionEnd(), false); } else { - cursorForward(0, layoutDirection() == Qt::LeftToRight ? 1 : -1); + cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); } } else if (event == QKeySequence::SelectNextChar) { - cursorForward(1, layoutDirection() == Qt::LeftToRight ? 1 : -1); + cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); } else if (event == QKeySequence::MoveToPreviousChar) { #if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) @@ -1672,11 +1675,11 @@ void QLineControl::processKeyEvent(QKeyEvent* event) #endif moveCursor(selectionStart(), false); } else { - cursorForward(0, layoutDirection() == Qt::LeftToRight ? -1 : 1); + cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); } } else if (event == QKeySequence::SelectPreviousChar) { - cursorForward(1, layoutDirection() == Qt::LeftToRight ? -1 : 1); + cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); } else if (event == QKeySequence::MoveToNextWord) { if (echoMode() == QLineEdit::Normal) diff --git a/src/gui/widgets/qlinecontrol_p.h b/src/gui/widgets/qlinecontrol_p.h index 7f3cad6..9764ba9 100644 --- a/src/gui/widgets/qlinecontrol_p.h +++ b/src/gui/widgets/qlinecontrol_p.h @@ -160,6 +160,8 @@ public: int cursorWidth() const { return m_cursorWidth; } void setCursorWidth(int value) { m_cursorWidth = value; } + Qt::CursorMoveStyle cursorMoveStyle() const { return m_textLayout.cursorMoveStyle(); } + void setCursorMoveStyle(Qt::CursorMoveStyle style) { m_textLayout.setCursorMoveStyle(style); } void moveCursor(int pos, bool mark = false); void cursorForward(bool mark, int steps) @@ -167,10 +169,12 @@ public: int c = m_cursor; if (steps > 0) { while (steps--) - c = m_textLayout.nextCursorPosition(c); + c = cursorMoveStyle() == Qt::VisualMoveStyle ? m_textLayout.rightCursorPosition(c) + : m_textLayout.nextCursorPosition(c); } else if (steps < 0) { while (steps++) - c = m_textLayout.previousCursorPosition(c); + c = cursorMoveStyle() == Qt::VisualMoveStyle ? m_textLayout.leftCursorPosition(c) + : m_textLayout.previousCursorPosition(c); } moveCursor(c, mark); } diff --git a/src/gui/widgets/qlineedit.cpp b/src/gui/widgets/qlineedit.cpp index 07bd273..3c9874e 100644 --- a/src/gui/widgets/qlineedit.cpp +++ b/src/gui/widgets/qlineedit.cpp @@ -1112,6 +1112,34 @@ void QLineEdit::setDragEnabled(bool b) /*! + \property QLineEdit::cursorMoveStyle + \brief the movement style of cursor in this line edit + \since 4.8 + + When this property is set to Qt::VisualMoveStyle, the line edit will use visual + movement style. Pressing the left arrow key will always cause the cursor to move + left, regardless of the text's writing direction. The same behavior applies to + right arrow key. + + When the property is Qt::LogicalMoveStyle (the default), within a LTR text block, + increase cursor position when pressing left arrow key, decrease cursor position + when pressing the right arrow key. If the text block is right to left, the opposite + behavior applies. +*/ + +Qt::CursorMoveStyle QLineEdit::cursorMoveStyle() const +{ + Q_D(const QLineEdit); + return d->control->cursorMoveStyle(); +} + +void QLineEdit::setCursorMoveStyle(Qt::CursorMoveStyle style) +{ + Q_D(QLineEdit); + d->control->setCursorMoveStyle(style); +} + +/*! \property QLineEdit::acceptableInput \brief whether the input satisfies the inputMask and the validator. diff --git a/src/gui/widgets/qlineedit.h b/src/gui/widgets/qlineedit.h index 636cee7..e88273f 100644 --- a/src/gui/widgets/qlineedit.h +++ b/src/gui/widgets/qlineedit.h @@ -43,6 +43,7 @@ #define QLINEEDIT_H #include <QtGui/qframe.h> +#include <QtGui/qtextcursor.h> #include <QtCore/qstring.h> #include <QtCore/qmargins.h> @@ -84,6 +85,7 @@ class Q_GUI_EXPORT QLineEdit : public QWidget Q_PROPERTY(bool redoAvailable READ isRedoAvailable) Q_PROPERTY(bool acceptableInput READ hasAcceptableInput) Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText) + Q_PROPERTY(Qt::CursorMoveStyle cursorMoveStyle READ cursorMoveStyle WRITE setCursorMoveStyle) public: explicit QLineEdit(QWidget* parent=0); @@ -158,6 +160,9 @@ public: void setDragEnabled(bool b); bool dragEnabled() const; + void setCursorMoveStyle(Qt::CursorMoveStyle style); + Qt::CursorMoveStyle cursorMoveStyle() const; + QString inputMask() const; void setInputMask(const QString &inputMask); bool hasAcceptableInput() const; diff --git a/src/gui/widgets/qmainwindow.cpp b/src/gui/widgets/qmainwindow.cpp index 43d6796..e39e595 100644 --- a/src/gui/widgets/qmainwindow.cpp +++ b/src/gui/widgets/qmainwindow.cpp @@ -78,7 +78,6 @@ public: : layout(0), explicitIconSize(false), toolButtonStyle(Qt::ToolButtonIconOnly) #ifdef Q_WS_MAC , useHIToolBar(false) - , activateUnifiedToolbarAfterFullScreen(false) #endif #if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_CURSOR) , hasOldCursor(false) , cursorAdjusted(false) @@ -90,7 +89,6 @@ public: Qt::ToolButtonStyle toolButtonStyle; #ifdef Q_WS_MAC bool useHIToolBar; - bool activateUnifiedToolbarAfterFullScreen; #endif void init(); QList<int> hoverSeparator; diff --git a/src/gui/widgets/qmainwindowlayout.cpp b/src/gui/widgets/qmainwindowlayout.cpp index d4afe07..8880ca9 100644 --- a/src/gui/widgets/qmainwindowlayout.cpp +++ b/src/gui/widgets/qmainwindowlayout.cpp @@ -1699,6 +1699,7 @@ QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLay , gapIndicator(new QRubberBand(QRubberBand::Rectangle, mainwindow)) #endif //QT_NO_RUBBERBAND #ifdef Q_WS_MAC + , activateUnifiedToolbarAfterFullScreen(false) , blockVisiblityCheck(false) #endif { diff --git a/src/gui/widgets/qmainwindowlayout_p.h b/src/gui/widgets/qmainwindowlayout_p.h index 20aca61..0442510 100644 --- a/src/gui/widgets/qmainwindowlayout_p.h +++ b/src/gui/widgets/qmainwindowlayout_p.h @@ -338,7 +338,6 @@ public: void removeFromMacToolbar(QToolBar *toolbar); void cleanUpMacToolbarItems(); void fixSizeInUnifiedToolbar(QToolBar *tb) const; - bool useHIToolBar; bool activateUnifiedToolbarAfterFullScreen; void syncUnifiedToolbarVisibility(); bool blockVisiblityCheck; diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index b0ea00f..1dac661 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -82,6 +82,10 @@ # include <private/qt_cocoa_helpers_mac_p.h> #endif +#ifdef Q_WS_S60 +# include "private/qt_s60_p.h" +#endif + QT_BEGIN_NAMESPACE @@ -172,6 +176,14 @@ void QMenuPrivate::init() q->addAction(selectAction); q->addAction(cancelAction); #endif + +#ifdef Q_WS_S60 + if (S60->avkonComponentsSupportTransparency) { + bool noSystemBackground = q->testAttribute(Qt::WA_NoSystemBackground); + q->setAttribute(Qt::WA_TranslucentBackground); // also sets WA_NoSystemBackground + q->setAttribute(Qt::WA_NoSystemBackground, noSystemBackground); // restore system background attribute + } +#endif } int QMenuPrivate::scrollerHeight() const diff --git a/src/gui/widgets/qplaintextedit.cpp b/src/gui/widgets/qplaintextedit.cpp index 7435691..51c4ccb 100644 --- a/src/gui/widgets/qplaintextedit.cpp +++ b/src/gui/widgets/qplaintextedit.cpp @@ -483,6 +483,7 @@ int QPlainTextEditPrivate::verticalOffset(int topBlock, int topLine) const QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout()); Q_ASSERT(documentLayout); QRectF r = documentLayout->blockBoundingRect(currentBlock); + Q_UNUSED(r); QTextLayout *layout = currentBlock.layout(); if (layout && topLine <= layout->lineCount()) { QTextLine line = layout->lineAt(topLine - 1); @@ -648,6 +649,11 @@ void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx) } control->topBlock = blockNumber; topLine = lineNumber; + + bool vbarSignalsBlocked = vbar->blockSignals(true); + vbar->setValue(block.firstLineNumber() + lineNumber); + vbar->blockSignals(vbarSignalsBlocked); + if (dx || dy) viewport->scroll(q->isRightToLeft() ? -dx : dx, dy); else diff --git a/src/gui/widgets/qtextedit.cpp b/src/gui/widgets/qtextedit.cpp index ff924bf..8df436f 100644 --- a/src/gui/widgets/qtextedit.cpp +++ b/src/gui/widgets/qtextedit.cpp @@ -2614,7 +2614,6 @@ Qt::TextFormat QTextEdit::textFormat() const void QTextEdit::append(const QString &text) { Q_D(QTextEdit); - QTextBlock lastBlock = d->control->document()->lastBlock(); const bool atBottom = isReadOnly() ? d->verticalOffset() >= d->vbar->maximum() : d->control->textCursor().atEnd(); d->control->append(text); diff --git a/src/gui/widgets/qworkspace.cpp b/src/gui/widgets/qworkspace.cpp index bf50d07..13ef13b 100644 --- a/src/gui/widgets/qworkspace.cpp +++ b/src/gui/widgets/qworkspace.cpp @@ -1239,7 +1239,6 @@ QWidget * QWorkspace::addWindow(QWidget *w, Qt::WindowFlags flags) int x = w->x(); int y = w->y(); bool hasPos = w->testAttribute(Qt::WA_Moved); - QSize s = w->size().expandedTo(qSmartMinSize(w)); if (!hasSize && w->sizeHint().isValid()) w->adjustSize(); |