diff options
author | Jan-Arve Sæther <jan-arve.saether@nokia.com> | 2009-10-28 06:53:39 (GMT) |
---|---|---|
committer | Jan-Arve Sæther <jan-arve.saether@nokia.com> | 2009-10-28 06:53:39 (GMT) |
commit | 262d0df3b166fecb3502e81b2ab85cadd71ae70f (patch) | |
tree | 17f8cba9c8f1ff4f46b45386c79ff9ebb3f998be /src/gui/graphicsview | |
parent | df0001a3d62938c713b351c7e59228b803ec5670 (diff) | |
parent | 1607216cc6292ef9a4af68ce6d29dc79fffea92c (diff) | |
download | Qt-262d0df3b166fecb3502e81b2ab85cadd71ae70f.zip Qt-262d0df3b166fecb3502e81b2ab85cadd71ae70f.tar.gz Qt-262d0df3b166fecb3502e81b2ab85cadd71ae70f.tar.bz2 |
Merge branch 'fixes' of git://gitorious.org/~fleury/qt/fleury-openbossa-clone into openbossa-fleury-fixes3
Conflicts:
src/gui/graphicsview/qgraphicsanchorlayout_p.cpp
src/gui/graphicsview/qgraphicsanchorlayout_p.h
Diffstat (limited to 'src/gui/graphicsview')
-rw-r--r-- | src/gui/graphicsview/qgraphicsanchorlayout.cpp | 122 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsanchorlayout_p.cpp | 326 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsanchorlayout_p.h | 28 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsitem.cpp | 48 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsitem.h | 3 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsitem_p.h | 13 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsscene.cpp | 258 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsscene_p.h | 7 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicstransform.cpp | 4 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsview.cpp | 13 | ||||
-rw-r--r-- | src/gui/graphicsview/qsimplex_p.cpp | 111 | ||||
-rw-r--r-- | src/gui/graphicsview/qsimplex_p.h | 38 |
12 files changed, 756 insertions, 215 deletions
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout.cpp b/src/gui/graphicsview/qgraphicsanchorlayout.cpp index 00d3478..22a7cf9 100644 --- a/src/gui/graphicsview/qgraphicsanchorlayout.cpp +++ b/src/gui/graphicsview/qgraphicsanchorlayout.cpp @@ -48,36 +48,60 @@ \ingroup geomanagement \ingroup graphicsview-api - The anchor layout is a layout where one can specify how widgets should be placed relative to - each other. The specification is called an anchor, and it is set up by calling anchor(). + The anchor layout allows developers to specify how widgets should be placed relative to + each other, and to the layout itself. The specification is made by adding anchors to the + layout by calling addAnchor(), addAnchors() or addCornerAnchors(). + + Existing anchors in the layout can be accessed with the anchor() function. + Items that are anchored are automatically added to the layout, and if items + are removed, all their anchors will be automatically removed. + + \beginfloatleft + \inlineimage simpleanchorlayout-example.png Using an anchor layout to align simple colored widgets. + \endfloat + Anchors are always set up between edges of an item, where the "center" is also considered to - be an edge. Considering this example: - \code - QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout; - QGraphicsWidget *a = new QGraphicsWidget; - QGraphicsWidget *b = new QGraphicsWidget; - l->anchor(a, Qt::AnchorRight, b, Qt::AnchorLeft); - \endcode - - Here is the right edge of item A anchored to the left edge of item B, with the result that - item B will be placed to the right of item A, with a spacing between A and B. If the - spacing is negative, the items will overlap to some extent. Items that are anchored are - automatically added to the layout, and if items are removed, all their anchors will be - automatically removed - - \section1 Size Hints and Size Policies in QGraphicsAnchorLayout + be an edge. Consider the following example: + + \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding anchors + + Here, the right edge of item \c a is anchored to the left edge of item \c b and the bottom + edge of item \c a is anchored to the top edge of item \c b, with the result that + item \c b will be placed diagonally to the right and below item \c b. + + The addCornerAnchors() function provides a simpler way of anchoring the corners + of two widgets than the two individual calls to addAnchor() shown in the code + above. Here, we see how a widget can be anchored to the top-left corner of the enclosing + layout: + + \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding a corner anchor + + In cases where anchors are used to match the widths or heights of widgets, it is + convenient to use the addAnchors() function. As with the other functions for specifying + anchors, it can also be used to anchor a widget to a layout. + + \clearfloat + \section1 Size Hints and Size Policies in an Anchor Layout QGraphicsAnchorLayout respects each item's size hints and size policies. However it does - not respect stretch factors currently. This might change in the future, so please refrain - from using stretch factors in anchor layout to avoid any future regressions. + not currently respect their stretch factors. This might change in the future, so avoid + using stretch factors in anchor layouts if you want to avoid any future regressions in + behavior. + + \section1 Spacing within an Anchor Layout + + The layout may distribute some space between the items. If the spacing has not been + explicitly specified, the actual amount of space will usually be 0. + + However, if the first edge is the \e opposite of the second edge (e.g., the right edge + of the first widget is anchored to the left edge of the second widget), the size of the + anchor will be queried from the style through a pixel metric: + \l{QStyle::}{PM_LayoutHorizontalSpacing} for horizontal anchors and + \l{QStyle::}{PM_LayoutVerticalSpacing} for vertical anchors. - \section1 Spacing within QGraphicsAnchorLayout + If the spacing is negative, the items will overlap to some extent. - Between the items, the layout can distribute some space. If the spacing has not been - explicitly specified, the actual amount of space will usually be 0, but if the first edge - is the "opposite" of the second edge (i.e. Right is anchored to Left or vice-versa), the - size of the anchor will be queried from the style through the pixelMetric - PM_LayoutHorizontalSpacing (or PM_LayoutVerticalSpacing for vertical anchors). + \sa QGraphicsLinearLayout, QGraphicsGridLayout, QGraphicsLayout */ /*! @@ -215,7 +239,7 @@ QGraphicsAnchorLayout::~QGraphicsAnchorLayout() If there is already an anchor between the edges, the the new anchor will replace the old one. \a firstItem and \a secondItem are automatically added to the layout if they are not part - of the layout. This means that count() can increase with up to 2. + of the layout. This means that count() can increase by up to 2. The spacing an anchor will get depends on the type of anchor. For instance, anchors from the Right edge of one item to the Left edge of another (or vice versa) will use the default @@ -228,7 +252,7 @@ QGraphicsAnchorLayout::~QGraphicsAnchorLayout() Calling this function where \a firstItem or \a secondItem are ancestors of the layout have undefined behaviour. - \sa addCornerAnchors(), addAnchors() + \sa addAnchors(), addCornerAnchors() */ QGraphicsAnchor * QGraphicsAnchorLayout::addAnchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint firstEdge, @@ -253,29 +277,26 @@ QGraphicsAnchorLayout::anchor(QGraphicsLayoutItem *firstItem, Qt::AnchorPoint fi } /*! - Creates two anchors between \a firstItem and \a secondItem, where one is for the horizontal - edge and another one for the vertical edge that the corners \a firstCorner and \a - secondCorner specifies. - The magnitude of the anchors is picked up from the style. + Creates two anchors between \a firstItem and \a secondItem specified by the corners, + \a firstCorner and \a secondCorner, where one is for the horizontal edge and another + one for the vertical edge. - This is a convenience function, since anchoring corners can be expressed as anchoring two edges. - For instance, - \code - layout->addAnchor(layout, Qt::AnchorTop, b, Qt::AnchorTop); - layout->addAnchor(layout, Qt::AnchorLeft, b, Qt::AnchorLeft); - \endcode + This is a convenience function, since anchoring corners can be expressed as anchoring + two edges. For instance: - has the same effect as + \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding a corner anchor in two steps - \code - layout->addCornerAnchors(layout, Qt::TopLeft, b, Qt::TopLeft); - \endcode + This can also be achieved with the following line of code: + + \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding a corner anchor If there is already an anchor between the edge pairs, it will be replaced by the anchors that this function specifies. \a firstItem and \a secondItem are automatically added to the layout if they are not part of the - layout. This means that count() can increase with up to 2. + layout. This means that count() can increase by up to 2. + + \sa addAnchor(), addAnchors() */ void QGraphicsAnchorLayout::addCornerAnchors(QGraphicsLayoutItem *firstItem, Qt::Corner firstCorner, @@ -302,17 +323,16 @@ void QGraphicsAnchorLayout::addCornerAnchors(QGraphicsLayoutItem *firstItem, edges of \a secondItem, so that \a firstItem has the same size as \a secondItem in the dimensions specified by \a orientations. - Calling this convenience function with the following arguments - \code - l->addAnchors(firstItem, secondItem, Qt::Horizontal) - \endcode + For example, the following example anchors the left and right edges of two items + to match their widths: + + \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding anchors to match sizes in two steps + + This can also be achieved using the following line of code: - is the same as + \snippet examples/graphicsview/simpleanchorlayout/main.cpp adding anchors to match sizes - \code - l->addAnchor(firstItem, Qt::AnchorLeft, secondItem, Qt::AnchorLeft); - l->addAnchor(firstItem, Qt::AnchorRight, secondItem, Qt::AnchorRight); - \endcode + \sa addAnchor(), addCornerAnchors() */ void QGraphicsAnchorLayout::addAnchors(QGraphicsLayoutItem *firstItem, QGraphicsLayoutItem *secondItem, diff --git a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp index 5f7d5b9..1d6e29d 100644 --- a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp +++ b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp @@ -142,34 +142,25 @@ static void internalSizeHints(QSizePolicy::Policy policy, *expSize = *prefSize; } -void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) +bool AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) { - const bool isInternalAnchor = from->m_item == to->m_item; - QSizePolicy::Policy policy; qreal minSizeHint; qreal prefSizeHint; qreal maxSizeHint; - if (isInternalAnchor) { - const QGraphicsAnchorLayoutPrivate::Orientation orient = - QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge); - const Qt::AnchorPoint centerEdge = - QGraphicsAnchorLayoutPrivate::pickEdge(Qt::AnchorHorizontalCenter, orient); - bool hasCenter = (from->m_edge == centerEdge || to->m_edge == centerEdge); - + // It is an internal anchor + if (item) { if (isLayoutAnchor) { minSize = 0; prefSize = 0; expSize = 0; maxSize = QWIDGETSIZE_MAX; - if (hasCenter) + if (isCenterAnchor) maxSize /= 2; - return; + return true; } else { - - QGraphicsLayoutItem *item = from->m_item; - if (orient == QGraphicsAnchorLayoutPrivate::Horizontal) { + if (orientation == QGraphicsAnchorLayoutPrivate::Horizontal) { policy = item->sizePolicy().horizontalPolicy(); minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).width(); prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).width(); @@ -181,7 +172,7 @@ void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).height(); } - if (hasCenter) { + if (isCenterAnchor) { minSizeHint /= 2; prefSizeHint /= 2; maxSizeHint /= 2; @@ -228,6 +219,8 @@ void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) sizeAtPreferred = prefSize; sizeAtExpanding = prefSize; sizeAtMaximum = prefSize; + + return true; } void ParallelAnchorData::updateChildrenSizes() @@ -241,26 +234,29 @@ void ParallelAnchorData::updateChildrenSizes() secondEdge->updateChildrenSizes(); } -void ParallelAnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) +bool ParallelAnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) { - refreshSizeHints_helper(styleInfo); + return refreshSizeHints_helper(styleInfo); } -void ParallelAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, +bool ParallelAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, bool refreshChildren) { - if (refreshChildren) { - firstEdge->refreshSizeHints(styleInfo); - secondEdge->refreshSizeHints(styleInfo); + if (refreshChildren && (!firstEdge->refreshSizeHints(styleInfo) + || !secondEdge->refreshSizeHints(styleInfo))) { + return false; } - // ### should we warn if the parallel connection is invalid? - // e.g. 1-2-3 with 10-20-30, the minimum of the latter is - // bigger than the maximum of the former. - minSize = qMax(firstEdge->minSize, secondEdge->minSize); maxSize = qMin(firstEdge->maxSize, secondEdge->maxSize); + // This condition means that the maximum size of one anchor being simplified is smaller than + // the minimum size of the other anchor. The consequence is that there won't be a valid size + // for this parallel setup. + if (minSize > maxSize) { + return false; + } + expSize = qMax(firstEdge->expSize, secondEdge->expSize); expSize = qMin(expSize, maxSize); @@ -272,6 +268,8 @@ void ParallelAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *styleIn sizeAtPreferred = prefSize; sizeAtExpanding = prefSize; sizeAtMaximum = prefSize; + + return true; } /*! @@ -376,12 +374,12 @@ void SequentialAnchorData::updateChildrenSizes() } } -void SequentialAnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) +bool SequentialAnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo) { - refreshSizeHints_helper(styleInfo); + return refreshSizeHints_helper(styleInfo); } -void SequentialAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, +bool SequentialAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, bool refreshChildren) { minSize = 0; @@ -393,8 +391,8 @@ void SequentialAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *style AnchorData *edge = m_edges.at(i); // If it's the case refresh children information first - if (refreshChildren) - edge->refreshSizeHints(styleInfo); + if (refreshChildren && !edge->refreshSizeHints(styleInfo)) + return false; minSize += edge->minSize; prefSize += edge->prefSize; @@ -407,6 +405,8 @@ void SequentialAnchorData::refreshSizeHints_helper(const QLayoutStyleInfo *style sizeAtPreferred = prefSize; sizeAtExpanding = prefSize; sizeAtMaximum = prefSize; + + return true; } #ifdef QT_DEBUG @@ -524,18 +524,49 @@ inline static qreal checkAdd(qreal a, qreal b) } /*! - * \internal - * - * Takes the sequence of vertices described by (\a before, \a vertices, \a after) and replaces - * all anchors connected to the vertices in \a vertices with one simplified anchor between - * \a before and \a after. The simplified anchor will be a placeholder for all the previous - * anchors between \a before and \a after, and can be restored back to the anchors it is a - * placeholder for. - */ -static bool simplifySequentialChunk(Graph<AnchorVertex, AnchorData> *graph, - AnchorVertex *before, - const QVector<AnchorVertex*> &vertices, - AnchorVertex *after) + \internal + + Adds \a newAnchor to the graph \a g. + + Returns the newAnchor itself if it could be added without further changes to the graph. If a + new parallel anchor had to be created, then returns the new parallel anchor. In case the + addition is unfeasible -- because a parallel setup is not possible, returns 0. +*/ +static AnchorData *addAnchorMaybeParallel(Graph<AnchorVertex, AnchorData> *g, + AnchorData *newAnchor) +{ + bool feasible = true; + + // If already exists one anchor where newAnchor is supposed to be, we create a parallel + // anchor. + if (AnchorData *oldAnchor = g->takeEdge(newAnchor->from, newAnchor->to)) { + ParallelAnchorData *parallel = new ParallelAnchorData(oldAnchor, newAnchor); + + // At this point we can identify that the parallel anchor is not feasible, e.g. one + // anchor minimum size is bigger than the other anchor maximum size. + feasible = parallel->refreshSizeHints_helper(0, false); + newAnchor = parallel; + } + + g->createEdge(newAnchor->from, newAnchor->to, newAnchor); + return feasible ? newAnchor : 0; +} + + +/*! + \internal + + Takes the sequence of vertices described by (\a before, \a vertices, \a after) and removes + all anchors connected to the vertices in \a vertices, returning one simplified anchor between + \a before and \a after. + + Note that this function doesn't add the created anchor to the graph. This should be done by + the caller. +*/ +static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph, + AnchorVertex *before, + const QVector<AnchorVertex*> &vertices, + AnchorVertex *after) { AnchorData *data = graph->edgeData(before, vertices.first()); Q_ASSERT(data); @@ -577,24 +608,7 @@ static bool simplifySequentialChunk(Graph<AnchorVertex, AnchorData> *graph, sequence->refreshSizeHints_helper(0, false); - // Note that since layout 'edges' can't be simplified away from - // the graph, it's safe to assume that if there's a layout - // 'edge', it'll be in the boundaries of the sequence. - sequence->isLayoutAnchor = (sequence->m_edges.first()->isLayoutAnchor - || sequence->m_edges.last()->isLayoutAnchor); - - AnchorData *newAnchor = sequence; - if (AnchorData *oldAnchor = graph->takeEdge(before, after)) { - ParallelAnchorData *parallel = new ParallelAnchorData(oldAnchor, sequence); - parallel->isLayoutAnchor = (oldAnchor->isLayoutAnchor - || sequence->isLayoutAnchor); - parallel->refreshSizeHints_helper(0, false); - newAnchor = parallel; - } - graph->createEdge(before, after, newAnchor); - - // True if we created a parallel anchor - return newAnchor != sequence; + return sequence; } /*! @@ -631,15 +645,17 @@ static bool simplifySequentialChunk(Graph<AnchorVertex, AnchorData> *graph, 2. Go to (1) 3. Done + When creating the parallel anchors, the algorithm might identify unfeasible situations. In this + case the simplification process stops and returns false. Otherwise returns true. */ -void QGraphicsAnchorLayoutPrivate::simplifyGraph(Orientation orientation) +bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Orientation orientation) { static bool noSimplification = !qgetenv("QT_ANCHORLAYOUT_NO_SIMPLIFICATION").isEmpty(); if (noSimplification || items.isEmpty()) - return; + return true; if (graphSimplified[orientation]) - return; + return true; graphSimplified[orientation] = true; #if 0 @@ -648,12 +664,18 @@ void QGraphicsAnchorLayoutPrivate::simplifyGraph(Orientation orientation) #endif if (!graph[orientation].rootVertex()) - return; + return true; bool dirty; + bool feasible = true; do { - dirty = simplifyGraphIteration(orientation); - } while (dirty); + dirty = simplifyGraphIteration(orientation, &feasible); + } while (dirty && feasible); + + if (!feasible) + graphSimplified[orientation] = false; + + return feasible; } /*! @@ -670,7 +692,8 @@ void QGraphicsAnchorLayoutPrivate::simplifyGraph(Orientation orientation) Note that there are some catches to this that are not covered by the above explanation, see the function comments for more details. */ -bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutPrivate::Orientation orientation) +bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutPrivate::Orientation orientation, + bool *feasible) { Q_Q(QGraphicsAnchorLayout); Graph<AnchorVertex, AnchorData> &g = graph[orientation]; @@ -681,8 +704,6 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP QVector<AnchorVertex*> candidates; bool candidatesForward; - const Qt::AnchorPoint centerEdge = pickEdge(Qt::AnchorHorizontalCenter, orientation); - // Walk depth-first, in the stack we store start of the candidate sequence (beforeSequence) // and the vertex to be visited. while (!stack.isEmpty()) { @@ -791,7 +812,8 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP // One restriction we have is to not simplify half of an anchor and let the other half // unsimplified. So we remove center edges before and after the sequence. - if (beforeSequence->m_edge == centerEdge && beforeSequence->m_item == candidates.first()->m_item) { + const AnchorData *firstAnchor = g.edgeData(beforeSequence, candidates.first()); + if (firstAnchor->isCenterAnchor) { beforeSequence = candidates.first(); candidates.remove(0); @@ -800,7 +822,8 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP continue; } - if (afterSequence->m_edge == centerEdge && afterSequence->m_item == candidates.last()->m_item) { + const AnchorData *lastAnchor = g.edgeData(candidates.last(), afterSequence); + if (lastAnchor->isCenterAnchor) { afterSequence = candidates.last(); candidates.remove(candidates.count() - 1); @@ -808,11 +831,26 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(QGraphicsAnchorLayoutP continue; } - // This function will remove the candidates from the graph and create one edge between - // beforeSequence and afterSequence. This function returns true if the sequential - // simplification also caused a parallel simplification to be created. In this case we end - // the iteration and start again (since all the visited state we have may be outdated). - if (simplifySequentialChunk(&g, beforeSequence, candidates, afterSequence)) + // + // Add the sequence to the graph. + // + + AnchorData *sequence = createSequence(&g, beforeSequence, candidates, afterSequence); + + // If 'beforeSequence' and 'afterSequence' already had an anchor between them, we'll + // create a parallel anchor between the new sequence and the old anchor. + AnchorData *newAnchor = addAnchorMaybeParallel(&g, sequence); + + if (!newAnchor) { + *feasible = false; + return false; + } + + // When a new parallel anchor is create in the graph, we finish the iteration and return + // true to indicate a new iteration is needed. This happens because a parallel anchor + // changes the number of adjacents one vertex has, possibly opening up oportunities for + // building candidate lists (when adjacents == 2). + if (newAnchor != sequence) return true; // If there was no parallel simplification, we'll keep walking the graph. So we clear the @@ -1022,11 +1060,13 @@ void QGraphicsAnchorLayoutPrivate::createCenterAnchors( AnchorData *data = new AnchorData; c->variables.insert(data, 1.0); addAnchor_helper(item, firstEdge, item, centerEdge, data); + data->isCenterAnchor = true; data->refreshSizeHints(0); data = new AnchorData; c->variables.insert(data, -1.0); addAnchor_helper(item, centerEdge, item, lastEdge, data); + data->isCenterAnchor = true; data->refreshSizeHints(0); itemCenterConstraints[orientation].append(c); @@ -1248,9 +1288,11 @@ void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstIt { Q_Q(QGraphicsAnchorLayout); + const Orientation orientation = edgeOrientation(firstEdge); + // Guarantee that the graph is no simplified when adding this anchor, // anchor manipulation always happen in the full graph - restoreSimplifiedGraph(edgeOrientation(firstEdge)); + restoreSimplifiedGraph(orientation); // Is the Vertex (firstItem, firstEdge) already represented in our // internal structure? @@ -1259,10 +1301,16 @@ void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstIt // Remove previous anchor // ### Could we update the existing edgeData rather than creating a new one? - if (graph[edgeOrientation(firstEdge)].edgeData(v1, v2)) { + if (graph[orientation].edgeData(v1, v2)) { removeAnchor_helper(v1, v2); } + // If its an internal anchor, set the associated item + if (firstItem == secondItem) + data->item = firstItem; + + data->orientation = orientation; + // Create a bi-directional edge in the sense it can be transversed both // from v1 or v2. "data" however is shared between the two references // so we still know that the anchor direction is from 1 to 2. @@ -1271,10 +1319,11 @@ void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstIt #ifdef QT_DEBUG data->name = QString::fromAscii("%1 --to--> %2").arg(v1->toString()).arg(v2->toString()); #endif - // Keep track of anchors that are connected to the layout 'edges' - data->isLayoutAnchor = (v1->m_item == q || v2->m_item == q); + // ### bit to track internal anchors, since inside AnchorData methods + // we don't have access to the 'q' pointer. + data->isLayoutAnchor = (data->item == q); - graph[edgeOrientation(firstEdge)].createEdge(v1, v2, data); + graph[orientation].createEdge(v1, v2, data); } QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::getAnchor(QGraphicsLayoutItem *firstItem, @@ -1439,7 +1488,7 @@ void QGraphicsAnchorLayoutPrivate::anchorSize(const AnchorData *data, Q_ASSERT(minSize || prefSize || maxSize); Q_ASSERT(data); QGraphicsAnchorLayoutPrivate *that = const_cast<QGraphicsAnchorLayoutPrivate *>(this); - that->restoreSimplifiedGraph(edgeOrientation(data->from->m_edge)); + that->restoreSimplifiedGraph(Orientation(data->orientation)); if (minSize) *minSize = data->minSize; @@ -1650,38 +1699,52 @@ QList<AnchorData *> getVariables(QList<QSimplexConstraint *> constraints) } /*! - \internal + \internal - Calculate graphs is the method that puts together all the helper routines - so that the AnchorLayout can calculate the sizes of each item. + Calculate graphs is the method that puts together all the helper routines + so that the AnchorLayout can calculate the sizes of each item. - In a nutshell it should do: + In a nutshell it should do: - 1) Update anchor nominal sizes, that is, the size that each anchor would - have if no other restrictions applied. This is done by quering the - layout style and the sizeHints of the items belonging to the layout. + 1) Refresh anchor nominal sizes, that is, the size that each anchor would + have if no other restrictions applied. This is done by quering the + layout style and the sizeHints of the items belonging to the layout. - 2) Simplify the graph by grouping together parallel and sequential anchors - into "group anchors". These have equivalent minimum, preferred and maximum - sizeHints as the anchors they replace. + 2) Simplify the graph by grouping together parallel and sequential anchors + into "group anchors". These have equivalent minimum, preferred and maximum + sizeHints as the anchors they replace. - 3) Check if we got to a trivial case. In some cases, the whole graph can be - simplified into a single anchor. If so, use this information. If not, - then call the Simplex solver to calculate the anchors sizes. + 3) Check if we got to a trivial case. In some cases, the whole graph can be + simplified into a single anchor. If so, use this information. If not, + then call the Simplex solver to calculate the anchors sizes. - 4) Once the root anchors had its sizes calculated, propagate that to the - anchors they represent. + 4) Once the root anchors had its sizes calculated, propagate that to the + anchors they represent. */ void QGraphicsAnchorLayoutPrivate::calculateGraphs( QGraphicsAnchorLayoutPrivate::Orientation orientation) { Q_Q(QGraphicsAnchorLayout); - // Simplify the graph - simplifyGraph(orientation); +#if defined(QT_DEBUG) || defined(Q_AUTOTEST_EXPORT) + lastCalculationUsedSimplex[orientation] = false; +#endif + + // Reset the nominal sizes of each anchor based on the current item sizes. This function + // works with both simplified and non-simplified graphs, so it'll work when the + // simplification is going to be reused. + if (!refreshAllSizeHints(orientation)) { + qWarning("QGraphicsAnchorLayout: anchor setup is not feasible."); + graphHasConflicts[orientation] = true; + return; + } - // Reset the nominal sizes of each anchor based on the current item sizes - setAnchorSizeHintsFromItems(orientation); + // Simplify the graph + if (!simplifyGraph(orientation)) { + qWarning("QGraphicsAnchorLayout: anchor setup is not feasible."); + graphHasConflicts[orientation] = true; + return; + } // Traverse all graph edges and store the possible paths to each vertex findPaths(orientation); @@ -1849,12 +1912,16 @@ bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(const QList<QSimplexConstra } /*! - \internal + \internal + + Traverse the graph refreshing the size hints. Complex anchors will call the + refresh method of their children anchors. Simple anchors, if are internal + anchors, will query the associated item for their size hints. - For graph edges ("anchors") that represent items, this method updates their - intrinsic size restrictions, based on the item size hints. + Returns false if some unfeasibility was found in the graph regarding the + complex anchors. */ -void QGraphicsAnchorLayoutPrivate::setAnchorSizeHintsFromItems(Orientation orientation) +bool QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Orientation orientation) { Graph<AnchorVertex, AnchorData> &g = graph[orientation]; QList<QPair<AnchorVertex *, AnchorVertex *> > vertices = g.connections(); @@ -1863,8 +1930,13 @@ void QGraphicsAnchorLayoutPrivate::setAnchorSizeHintsFromItems(Orientation orien for (int i = 0; i < vertices.count(); ++i) { AnchorData *data = g.edgeData(vertices.at(i).first, vertices.at(i).second);; Q_ASSERT(data->from && data->to); - data->refreshSizeHints(&styleInf); + + // During the traversal we check the feasibility of the complex anchors. + if (!data->refreshSizeHints(&styleInf)) + return false; } + + return true; } /*! @@ -1971,17 +2043,27 @@ QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHin { QList<QSimplexConstraint *> anchorConstraints; for (int i = 0; i < anchors.size(); ++i) { - QSimplexConstraint *c = new QSimplexConstraint; - c->variables.insert(anchors[i], 1.0); - c->constant = anchors[i]->minSize; - c->ratio = QSimplexConstraint::MoreOrEqual; - anchorConstraints += c; - - c = new QSimplexConstraint; - c->variables.insert(anchors[i], 1.0); - c->constant = anchors[i]->maxSize; - c->ratio = QSimplexConstraint::LessOrEqual; - anchorConstraints += c; + AnchorData *ad = anchors[i]; + + if ((ad->minSize == ad->maxSize) || qFuzzyCompare(ad->minSize, ad->maxSize)) { + QSimplexConstraint *c = new QSimplexConstraint; + c->variables.insert(ad, 1.0); + c->constant = ad->minSize; + c->ratio = QSimplexConstraint::Equal; + anchorConstraints += c; + } else { + QSimplexConstraint *c = new QSimplexConstraint; + c->variables.insert(ad, 1.0); + c->constant = ad->minSize; + c->ratio = QSimplexConstraint::MoreOrEqual; + anchorConstraints += c; + + c = new QSimplexConstraint; + c->variables.insert(ad, 1.0); + c->constant = ad->maxSize; + c->ratio = QSimplexConstraint::LessOrEqual; + anchorConstraints += c; + } } return anchorConstraints; @@ -2121,8 +2203,8 @@ void QGraphicsAnchorLayoutPrivate::identifyNonFloatItems_helper(const AnchorData switch(ad->type) { case AnchorData::Normal: - if (ad->from->m_item == ad->to->m_item && ad->to->m_item != q) - nonFloatingItemsIdentifiedSoFar->insert(ad->to->m_item); + if (ad->item && ad->item != q) + nonFloatingItemsIdentifiedSoFar->insert(ad->item); break; case AnchorData::Sequential: foreach (const AnchorData *d, static_cast<const SequentialAnchorData *>(ad)->m_edges) @@ -2388,7 +2470,7 @@ bool QGraphicsAnchorLayoutPrivate::solveMinMax(const QList<QSimplexConstraint *> *min = simplex.solveMin(); // Save sizeAtMinimum results - QList<QSimplexVariable *> variables = simplex.constraintsVariables(); + QList<AnchorData *> variables = getVariables(constraints); for (int i = 0; i < variables.size(); ++i) { AnchorData *ad = static_cast<AnchorData *>(variables[i]); Q_ASSERT(ad->result >= ad->minSize || qFuzzyCompare(ad->result, ad->minSize)); @@ -2547,7 +2629,7 @@ void QGraphicsAnchorLayoutPrivate::solveExpanding(const QList<QSimplexConstraint hasExpanding = true; // Lock anchor between boundedExpSize and sizeAtMaximum (ensure 3.a) - if (boundedExpSize == ad->sizeAtMaximum) { + if (boundedExpSize == ad->sizeAtMaximum || qFuzzyCompare(boundedExpSize, ad->sizeAtMaximum)) { // The interval has only one possible value, we can use an "Equal" // constraint and don't need to add this variable to the objective. QSimplexConstraint *itemC = new QSimplexConstraint; diff --git a/src/gui/graphicsview/qgraphicsanchorlayout_p.h b/src/gui/graphicsview/qgraphicsanchorlayout_p.h index 9b7d41e..99a866b 100644 --- a/src/gui/graphicsview/qgraphicsanchorlayout_p.h +++ b/src/gui/graphicsview/qgraphicsanchorlayout_p.h @@ -151,15 +151,16 @@ struct AnchorData : public QSimplexVariable { }; AnchorData() - : QSimplexVariable(), from(0), to(0), + : QSimplexVariable(), item(0), from(0), to(0), minSize(0), prefSize(0), expSize(0), maxSize(0), sizeAtMinimum(0), sizeAtPreferred(0), sizeAtExpanding(0), sizeAtMaximum(0), graphicsAnchor(0), skipInPreferred(0), - type(Normal), hasSize(true), isLayoutAnchor(false) {} + type(Normal), hasSize(true), isLayoutAnchor(false), + isCenterAnchor(false), orientation(0) {} virtual void updateChildrenSizes() {} - virtual void refreshSizeHints(const QLayoutStyleInfo *styleInfo); + virtual bool refreshSizeHints(const QLayoutStyleInfo *styleInfo); virtual ~AnchorData() {} @@ -180,6 +181,9 @@ struct AnchorData : public QSimplexVariable { hasSize = false; } + // Internal anchors have associated items + QGraphicsLayoutItem *item; + // Anchor is semantically directed AnchorVertex *from; AnchorVertex *to; @@ -205,7 +209,9 @@ struct AnchorData : public QSimplexVariable { uint skipInPreferred : 1; uint type : 2; // either Normal, Sequential or Parallel uint hasSize : 1; // if false, get size from style. - uint isLayoutAnchor : 1; // if this anchor is connected to a layout 'edge' + uint isLayoutAnchor : 1; // if this anchor is an internal layout anchor + uint isCenterAnchor : 1; + uint orientation : 1; }; #ifdef QT_DEBUG @@ -226,9 +232,9 @@ struct SequentialAnchorData : public AnchorData } virtual void updateChildrenSizes(); - virtual void refreshSizeHints(const QLayoutStyleInfo *styleInfo); + virtual bool refreshSizeHints(const QLayoutStyleInfo *styleInfo); - void refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, bool refreshChildren = true); + bool refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, bool refreshChildren = true); void setVertices(const QVector<AnchorVertex*> &vertices) { @@ -261,9 +267,9 @@ struct ParallelAnchorData : public AnchorData } virtual void updateChildrenSizes(); - virtual void refreshSizeHints(const QLayoutStyleInfo *styleInfo); + virtual bool refreshSizeHints(const QLayoutStyleInfo *styleInfo); - void refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, bool refreshChildren = true); + bool refreshSizeHints_helper(const QLayoutStyleInfo *styleInfo, bool refreshChildren = true); AnchorData* firstEdge; AnchorData* secondEdge; @@ -427,8 +433,8 @@ public: QLayoutStyleInfo &styleInfo() const; // Activation methods - void simplifyGraph(Orientation orientation); - bool simplifyGraphIteration(Orientation orientation); + bool simplifyGraph(Orientation orientation); + bool simplifyGraphIteration(Orientation orientation, bool *feasible); void restoreSimplifiedGraph(Orientation orientation); void calculateGraphs(); @@ -440,7 +446,7 @@ public: bool calculateNonTrunk(const QList<QSimplexConstraint *> &constraints, const QList<AnchorData *> &variables); - void setAnchorSizeHintsFromItems(Orientation orientation); + bool refreshAllSizeHints(Orientation orientation); void findPaths(Orientation orientation); void constraintsFromPaths(Orientation orientation); void updateAnchorSizes(Orientation orientation); diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index ad672a3..c38365b 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1228,7 +1228,7 @@ void QGraphicsItemCache::purge() } /*! - Constructs a QGraphicsItem with the given \a parent. + Constructs a QGraphicsItem, passing \a item to QGraphicsItem's constructor. It does not modify \fn QObject::parent(). If \a parent is 0, you can add the item to a scene by calling QGraphicsScene::addItem(). The item will then become a top-level item. @@ -2484,12 +2484,14 @@ void QGraphicsItem::setOpacity(qreal opacity) itemChange(ItemOpacityHasChanged, newOpacityVariant); // Update. - if (d_ptr->scene) + if (d_ptr->scene) { + d_ptr->invalidateGraphicsEffectsRecursively(); d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true, /*maybeDirtyClipPath=*/false, /*force=*/false, /*ignoreOpacity=*/true); + } if (d_ptr->isObject) emit static_cast<QGraphicsObject *>(this)->opacityChanged(); @@ -4951,6 +4953,22 @@ int QGraphicsItemPrivate::depth() const /*! \internal */ +void QGraphicsItemPrivate::invalidateGraphicsEffectsRecursively() +{ + QGraphicsItemPrivate *itemPrivate = this; + do { + if (itemPrivate->graphicsEffect) { + itemPrivate->notifyInvalidated = 1; + + if (!itemPrivate->updateDueToGraphicsEffect) + static_cast<QGraphicsItemEffectSourcePrivate *>(itemPrivate->graphicsEffect->d_func()->source->d_func())->invalidateCache(); + } + } while ((itemPrivate = itemPrivate->parent ? itemPrivate->parent->d_ptr.data() : 0)); +} + +/*! + \internal +*/ void QGraphicsItemPrivate::invalidateDepthRecursively() { if (itemDepth == -1) @@ -5282,11 +5300,7 @@ void QGraphicsItem::update(const QRectF &rect) return; // Make sure we notify effects about invalidated source. - QGraphicsItem *item = this; - do { - if (item->d_ptr->graphicsEffect) - item->d_ptr->notifyInvalidated = 1; - } while ((item = item->d_ptr->parent)); + d_ptr->invalidateGraphicsEffectsRecursively(); if (CacheMode(d_ptr->cacheMode) != NoCache) { // Invalidate cache. @@ -7304,7 +7318,7 @@ void QGraphicsObject::grabGesture(Qt::GestureType gesture, Qt::GestureContext co /*! \property QGraphicsObject::parent - \brief the parent of the item + \brief the parent of the item. It is independent from \fn QObject::parent. \sa QGraphicsItem::setParentItem(), QGraphicsItem::parentObject() */ @@ -10723,6 +10737,7 @@ QPixmap QGraphicsItemEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QP } pixmapPainter.end(); + return pixmap; } @@ -10742,6 +10757,23 @@ QDebug operator<<(QDebug debug, QGraphicsItem *item) return debug; } +QDebug operator<<(QDebug debug, QGraphicsObject *item) +{ + if (!item) { + debug << "QGraphicsObject(0)"; + return debug; + } + + debug.nospace() << item->metaObject()->className() << '(' << (void*)item; + if (!item->objectName().isEmpty()) + debug << ", name = " << item->objectName(); + debug.nospace() << ", parent = " << ((void*)item->parentItem()) + << ", pos = " << item->pos() + << ", z = " << item->zValue() << ", flags = " + << item->flags() << ')'; + return debug.space(); +} + QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change) { const char *str = "UnknownChange"; diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 2665235..f3fe99c 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -555,7 +555,7 @@ public: using QObject::children; #endif - void grabGesture(Qt::GestureType type, Qt::GestureContext context = Qt::WidgetWithChildrenGesture); + void grabGesture(Qt::GestureType type, Qt::GestureContext context = Qt::ItemWithChildrenGesture); Q_SIGNALS: void parentChanged(); @@ -1120,6 +1120,7 @@ template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item) #ifndef QT_NO_DEBUG_STREAM Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem *item); +Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsObject *item); Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change); Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag); Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 5b401ba..7c3c4f0 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -177,6 +177,7 @@ public: wantsActive(0), holesInSiblingIndex(0), sequentialOrdering(1), + updateDueToGraphicsEffect(0), globalStackingOrder(-1), q_ptr(0) { @@ -221,6 +222,7 @@ public: bool discardUpdateRequest(bool ignoreClipping = false, bool ignoreVisibleBit = false, bool ignoreDirtyBit = false, bool ignoreOpacity = false) const; int depth() const; + void invalidateGraphicsEffectsRecursively(); void invalidateDepthRecursively(); void resolveDepth(); void addChild(QGraphicsItem *child); @@ -502,6 +504,7 @@ public: quint32 wantsActive : 1; quint32 holesInSiblingIndex : 1; quint32 sequentialOrdering : 1; + quint32 updateDueToGraphicsEffect : 1; // Optional stacking order int globalStackingOrder; @@ -539,7 +542,7 @@ struct QGraphicsItemPrivate::TransformData QMatrix4x4 m; for (int i = 0; i < graphicsTransforms.size(); ++i) graphicsTransforms.at(i)->applyTo(&m); - x *= m.toTransform(0); + x *= m.toTransform(); } x.translate(xOrigin, yOrigin); x.rotate(rotation); @@ -589,8 +592,11 @@ public: inline const QWidget *widget() const { return 0; } - inline void update() - { item->update(); } + inline void update() { + item->d_ptr->updateDueToGraphicsEffect = true; + item->update(); + item->d_ptr->updateDueToGraphicsEffect = false; + } inline void effectBoundingRectChanged() { item->prepareGeometryChange(); } @@ -619,6 +625,7 @@ public: QGraphicsItem *item; QGraphicsItemPaintInfo *info; + QTransform lastEffectTransform; }; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 9736c3e..a62e486 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -242,7 +242,6 @@ #include <QtGui/qstyleoption.h> #include <QtGui/qtooltip.h> #include <QtGui/qtransform.h> -#include <QtGui/qgesture.h> #include <QtGui/qinputcontext.h> #include <QtGui/qgraphicseffect.h> #include <private/qapplication_p.h> @@ -251,6 +250,14 @@ #include <private/qt_x11_p.h> #endif #include <private/qgraphicseffect_p.h> +#include <private/qgesturemanager_p.h> + +// #define GESTURE_DEBUG +#ifndef GESTURE_DEBUG +# define DEBUG if (0) qDebug +#else +# define DEBUG qDebug +#endif QT_BEGIN_NAMESPACE @@ -1054,6 +1061,14 @@ bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event) */ bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event) { + if (QGraphicsObject *object = item->toGraphicsObject()) { + QApplicationPrivate *qAppPriv = QApplicationPrivate::instance(); + if (qAppPriv->gestureManager) { + if (qAppPriv->gestureManager->filterEvent(object, event)) + return true; + } + } + if (filterEvent(item, event)) return false; if (filterDescendantEvent(item, event)) @@ -3367,6 +3382,10 @@ bool QGraphicsScene::event(QEvent *event) case QEvent::TouchEnd: d->touchEventHandler(static_cast<QTouchEvent *>(event)); break; + case QEvent::Gesture: + case QEvent::GestureOverride: + d->gestureEventHandler(static_cast<QGestureEvent *>(event)); + break; default: return QObject::event(event); } @@ -4571,6 +4590,11 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * else painter->setWorldTransform(*transformPtr); painter->setOpacity(opacity); + + if (sourced->lastEffectTransform != painter->worldTransform()) { + sourced->lastEffectTransform = painter->worldTransform(); + sourced->invalidateCache(); + } item->d_ptr->graphicsEffect->draw(painter, source); painter->setWorldTransform(restoreTransform); sourced->info = 0; @@ -5701,6 +5725,238 @@ void QGraphicsScenePrivate::leaveModal(QGraphicsItem *panel) dispatchHoverEvent(&hoverEvent); } +void QGraphicsScenePrivate::getGestureTargets(const QSet<QGesture *> &gestures, + QWidget *viewport, + QMap<Qt::GestureType, QGesture *> *conflictedGestures, + QList<QList<QGraphicsObject *> > *conflictedItems, + QHash<QGesture *, QGraphicsObject *> *normalGestures) +{ + foreach (QGesture *gesture, gestures) { + Qt::GestureType gestureType = gesture->gestureType(); + if (gesture->hasHotSpot()) { + QPoint screenPos = gesture->hotSpot().toPoint(); + QList<QGraphicsItem *> items = itemsAtPosition(screenPos, QPointF(), viewport); + QList<QGraphicsObject *> result; + for (int j = 0; j < items.size(); ++j) { + QGraphicsObject *item = items.at(j)->toGraphicsObject(); + if (!item) + continue; + QGraphicsItemPrivate *d = item->QGraphicsItem::d_func(); + if (d->gestureContext.contains(gestureType)) { + result.append(item); + } + } + DEBUG() << "QGraphicsScenePrivate::getGestureTargets:" + << gesture << result; + if (result.size() == 1) { + normalGestures->insert(gesture, result.first()); + } else if (!result.isEmpty()) { + conflictedGestures->insert(gestureType, gesture); + conflictedItems->append(result); + } + } + } +} + +void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event) +{ + QWidget *viewport = event->widget(); + if (!viewport) + return; + QList<QGesture *> allGestures = event->allGestures(); + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "Delivering gestures:" << allGestures; + + typedef QHash<QGraphicsObject *, QList<QGesture *> > GesturesPerItem; + GesturesPerItem gesturesPerItem; + + QSet<QGesture *> startedGestures; + foreach (QGesture *gesture, allGestures) { + QGraphicsObject *target = gestureTargets.value(gesture, 0); + if (!target) { + // when we are not in started mode but don't have a target + // then the only one interested in gesture is the view/scene + if (gesture->state() == Qt::GestureStarted) + startedGestures.insert(gesture); + } else { + gesturesPerItem[target].append(gesture); + } + } + + QMap<Qt::GestureType, QGesture *> conflictedGestures; + QList<QList<QGraphicsObject *> > conflictedItems; + QHash<QGesture *, QGraphicsObject *> normalGestures; + getGestureTargets(startedGestures, viewport, &conflictedGestures, &conflictedItems, + &normalGestures); + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "Conflicting gestures:" << conflictedGestures.values() << conflictedItems; + Q_ASSERT((conflictedGestures.isEmpty() && conflictedItems.isEmpty()) || + (!conflictedGestures.isEmpty() && !conflictedItems.isEmpty())); + + // gestures that were sent as override events, but no one accepted them + QHash<QGesture *, QGraphicsObject *> ignoredConflictedGestures; + + // deliver conflicted gestures as override events first + while (!conflictedGestures.isEmpty() && !conflictedItems.isEmpty()) { + // get the topmost item to deliver the override event + Q_ASSERT(!conflictedItems.isEmpty()); + Q_ASSERT(!conflictedItems.first().isEmpty()); + QGraphicsObject *topmost = conflictedItems.first().first(); + for (int i = 1; i < conflictedItems.size(); ++i) { + QGraphicsObject *item = conflictedItems.at(i).first(); + if (qt_closestItemFirst(item, topmost)) { + topmost = item; + } + } + // get a list of gestures to send to the item + QList<Qt::GestureType> grabbedGestures = + topmost->QGraphicsItem::d_func()->gestureContext.keys(); + QList<QGesture *> gestures; + for (int i = 0; i < grabbedGestures.size(); ++i) { + if (QGesture *g = conflictedGestures.value(grabbedGestures.at(i), 0)) { + gestures.append(g); + if (!ignoredConflictedGestures.contains(g)) + ignoredConflictedGestures.insert(g, topmost); + } + } + + // send gesture override to the topmost item + QGestureEvent ev(gestures); + ev.t = QEvent::GestureOverride; + ev.setWidget(event->widget()); + // mark event and individual gestures as ignored + ev.ignore(); + foreach(QGesture *g, gestures) + ev.setAccepted(g, false); + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "delivering override to" + << topmost << gestures; + sendEvent(topmost, &ev); + // mark all accepted gestures to deliver them as normal gesture events + foreach (QGesture *g, gestures) { + if (ev.isAccepted() || ev.isAccepted(g)) { + conflictedGestures.remove(g->gestureType()); + gestureTargets.remove(g); + // add the gesture to the list of normal delivered gestures + normalGestures.insert(g, topmost); + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "override was accepted:" + << g << topmost; + ignoredConflictedGestures.remove(g); + } + } + // remove the item that we've already delivered from the list + for (int i = 0; i < conflictedItems.size(); ) { + QList<QGraphicsObject *> &items = conflictedItems[i]; + if (items.first() == topmost) { + items.removeFirst(); + if (items.isEmpty()) { + conflictedItems.removeAt(i); + continue; + } + } + ++i; + } + } + + // put back those started gestures that are not in the conflicted state + // and remember their targets + QHash<QGesture *, QGraphicsObject *>::const_iterator it = normalGestures.begin(), + e = normalGestures.end(); + for (; it != e; ++it) { + QGesture *g = it.key(); + QGraphicsObject *receiver = it.value(); + Q_ASSERT(!gestureTargets.contains(g)); + gestureTargets.insert(g, receiver); + gesturesPerItem[receiver].append(g); + } + it = ignoredConflictedGestures.begin(); + e = ignoredConflictedGestures.end(); + for (; it != e; ++it) { + QGesture *g = it.key(); + QGraphicsObject *receiver = it.value(); + Q_ASSERT(!gestureTargets.contains(g)); + gestureTargets.insert(g, receiver); + gesturesPerItem[receiver].append(g); + } + + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "Started gestures:" << normalGestures.keys() + << "All gestures:" << gesturesPerItem.values(); + + // deliver all events + QList<QGesture *> alreadyIgnoredGestures; + QHash<QGraphicsObject *, QSet<QGesture *> > itemIgnoredGestures; + QList<QGraphicsObject *> targetItems = gesturesPerItem.keys(); + qSort(targetItems.begin(), targetItems.end(), qt_closestItemFirst); + for (int i = 0; i < targetItems.size(); ++i) { + QGraphicsObject *item = targetItems.at(i); + QList<QGesture *> gestures = gesturesPerItem.value(item); + // remove gestures that were already delivered once and were ignored + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "already ignored gestures for item" + << item << ":" << itemIgnoredGestures.value(item); + + if (itemIgnoredGestures.contains(item)) // don't deliver twice to the same item + continue; + + QGraphicsItemPrivate *gid = item->QGraphicsItem::d_func(); + foreach(QGesture *g, alreadyIgnoredGestures) { + if (gid->gestureContext.contains(g->gestureType())) + gestures += g; + } + if (gestures.isEmpty()) + continue; + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "delivering to" + << item << gestures; + QGestureEvent ev(gestures); + ev.setWidget(event->widget()); + sendEvent(item, &ev); + QSet<QGesture *> ignoredGestures; + foreach (QGesture *g, gestures) { + if (!ev.isAccepted() && !ev.isAccepted(g)) + ignoredGestures.insert(g); + } + if (!ignoredGestures.isEmpty()) { + // get a list of items under the (current) hotspot of each ignored + // gesture and start delivery again from the beginning + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "item has ignored the event, will propagate." + << item << ignoredGestures; + itemIgnoredGestures[item] += ignoredGestures; + QMap<Qt::GestureType, QGesture *> conflictedGestures; + QList<QList<QGraphicsObject *> > itemsForConflictedGestures; + QHash<QGesture *, QGraphicsObject *> normalGestures; + getGestureTargets(ignoredGestures, viewport, + &conflictedGestures, &itemsForConflictedGestures, + &normalGestures); + QSet<QGraphicsObject *> itemsSet = targetItems.toSet(); + for (int k = 0; k < itemsForConflictedGestures.size(); ++k) + itemsSet += itemsForConflictedGestures.at(k).toSet(); + targetItems = itemsSet.toList(); + qSort(targetItems.begin(), targetItems.end(), qt_closestItemFirst); + alreadyIgnoredGestures = conflictedGestures.values(); + DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:" + << "new targets:" << targetItems; + i = -1; // start delivery again + continue; + } + } + + // forget about targets for gestures that have ended + foreach (QGesture *g, allGestures) { + switch (g->state()) { + case Qt::GestureFinished: + case Qt::GestureCanceled: + gestureTargets.remove(g); + break; + default: + break; + } + } +} + QT_END_NAMESPACE #include "moc_qgraphicsscene.cpp" diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 8073695..cd20fd0 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -282,6 +282,13 @@ public: bool allItemsIgnoreTouchEvents; void enableTouchEventsOnViews(); + QHash<QGesture *, QGraphicsObject *> gestureTargets; + void gestureEventHandler(QGestureEvent *event); + void getGestureTargets(const QSet<QGesture *> &gestures, QWidget *viewport, + QMap<Qt::GestureType, QGesture *> *conflictedGestures, + QList<QList<QGraphicsObject *> > *conflictedItems, + QHash<QGesture *, QGraphicsObject *> *normalGestures); + void updateInputMethodSensitivityInViews(); QList<QGraphicsItem *> modalPanels; diff --git a/src/gui/graphicsview/qgraphicstransform.cpp b/src/gui/graphicsview/qgraphicstransform.cpp index 49d8999..93dc196 100644 --- a/src/gui/graphicsview/qgraphicstransform.cpp +++ b/src/gui/graphicsview/qgraphicstransform.cpp @@ -547,9 +547,7 @@ void QGraphicsRotation::applyTo(QMatrix4x4 *matrix) const return; matrix->translate(d->origin); - QMatrix4x4 m; - m.rotate(d->angle, d->axis.x(), d->axis.y(), d->axis.z()); - *matrix *= m.toTransform(); + matrix->projectedRotate(d->angle, d->axis.x(), d->axis.y(), d->axis.z()); matrix->translate(-d->origin); } diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 49348de..f72aa8a 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -2701,6 +2701,19 @@ bool QGraphicsView::viewportEvent(QEvent *event) return true; } + case QEvent::Gesture: + case QEvent::GestureOverride: + { + if (!isEnabled()) + return false; + + if (d->scene && d->sceneInteractionAllowed) { + QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event); + gestureEvent->setWidget(viewport()); + (void) QApplication::sendEvent(d->scene, gestureEvent); + } + return true; + } default: break; } diff --git a/src/gui/graphicsview/qsimplex_p.cpp b/src/gui/graphicsview/qsimplex_p.cpp index b8f8fb4..86b10b4 100644 --- a/src/gui/graphicsview/qsimplex_p.cpp +++ b/src/gui/graphicsview/qsimplex_p.cpp @@ -108,10 +108,8 @@ void QSimplex::clearDataStructures() // Constraints for (int i = 0; i < constraints.size(); ++i) { delete constraints[i]->helper.first; - constraints[i]->helper.first = 0; - constraints[i]->helper.second = 0.0; delete constraints[i]->artificial; - constraints[i]->artificial = 0; + delete constraints[i]; } constraints.clear(); @@ -137,7 +135,23 @@ bool QSimplex::setConstraints(const QList<QSimplexConstraint *> newConstraints) if (newConstraints.isEmpty()) return true; // we are ok with no constraints - constraints = newConstraints; + + // Make deep copy of constraints. We need this copy because we may change + // them in the simplification method. + for (int i = 0; i < newConstraints.size(); ++i) { + QSimplexConstraint *c = new QSimplexConstraint; + c->constant = newConstraints[i]->constant; + c->ratio = newConstraints[i]->ratio; + c->variables = newConstraints[i]->variables; + constraints << c; + } + + // Remove constraints of type Var == K and replace them for their value. + if (!simplifyConstraints(&constraints)) { + qWarning() << "QSimplex: No feasible solution!"; + clearDataStructures(); + return false; + } /////////////////////////////////////// // Prepare variables and constraints // @@ -508,11 +522,21 @@ qreal QSimplex::solver(solverFactor factor) // Remove old objective clearRow(0); - // Set new objective + // Set new objective in the first row of the simplex matrix + qreal resultOffset = 0; QHash<QSimplexVariable *, qreal>::const_iterator iter; for (iter = objective->variables.constBegin(); iter != objective->variables.constEnd(); ++iter) { + + // Check if the variable was removed in the simplification process. + // If so, we save its offset to the objective function and skip adding + // it to the matrix. + if (iter.key()->index == -1) { + resultOffset += iter.value() * iter.key()->result; + continue; + } + setValueAt(0, iter.key()->index, -1 * factor * iter.value()); } @@ -525,7 +549,9 @@ qreal QSimplex::solver(solverFactor factor) } #endif - return factor * valueAt(0, columns - 1); + // Return the value calculated by the simplex plus the value of the + // fixed variables. + return (factor * valueAt(0, columns - 1)) + resultOffset; } /*! @@ -571,4 +597,77 @@ void QSimplex::collectResults() } } +/*! + \internal + + Looks for single-valued variables and remove them from the constraints list. +*/ +bool QSimplex::simplifyConstraints(QList<QSimplexConstraint *> *constraints) +{ + QHash<QSimplexVariable *, qreal> results; // List of single-valued variables + bool modified = true; // Any chance more optimization exists? + + while (modified) { + modified = false; + + // For all constraints + QList<QSimplexConstraint *>::iterator iter = constraints->begin(); + while (iter != constraints->end()) { + QSimplexConstraint *c = *iter; + if ((c->ratio == QSimplexConstraint::Equal) && (c->variables.count() == 1)) { + // Check whether this is a constraint of type Var == K + // If so, save its value to "results". + QSimplexVariable *variable = c->variables.constBegin().key(); + qreal result = c->constant / c->variables.value(variable); + + results.insert(variable, result); + variable->result = result; + variable->index = -1; + modified = true; + + } + + // Replace known values among their variables + QHash<QSimplexVariable *, qreal>::const_iterator r; + for (r = results.constBegin(); r != results.constEnd(); ++r) { + if (c->variables.contains(r.key())) { + c->constant -= r.value() * c->variables.take(r.key()); + modified = true; + } + } + + // Keep it normalized + if (c->constant < 0) + c->invert(); + + if (c->variables.isEmpty()) { + // If constraint became empty due to substitution, delete it. + if (c->isSatisfied() == false) + // We must ensure that the constraint soon to be deleted would not + // make the problem unfeasible if left behind. If that's the case, + // we return false so the simplex solver can properly report that. + return false; + + delete c; + iter = constraints->erase(iter); + } else { + ++iter; + } + } + } + + return true; +} + +void QSimplexConstraint::invert() +{ + constant = -constant; + ratio = Ratio(2 - ratio); + + QHash<QSimplexVariable *, qreal>::iterator iter; + for (iter = variables.begin(); iter != variables.end(); ++iter) { + iter.value() = -iter.value(); + } +} + QT_END_NAMESPACE diff --git a/src/gui/graphicsview/qsimplex_p.h b/src/gui/graphicsview/qsimplex_p.h index 51991a9..66ea739 100644 --- a/src/gui/graphicsview/qsimplex_p.h +++ b/src/gui/graphicsview/qsimplex_p.h @@ -63,7 +63,7 @@ struct QSimplexVariable QSimplexVariable() : result(0), index(0) {} qreal result; - uint index; + int index; }; @@ -95,7 +95,8 @@ struct QSimplexConstraint QPair<QSimplexVariable *, qreal> helper; QSimplexVariable * artificial; -#ifdef QT_DEBUG + void invert(); + bool isSatisfied() { qreal leftHandSide(0); @@ -106,7 +107,7 @@ struct QSimplexConstraint Q_ASSERT(constant > 0 || qFuzzyCompare(1, 1 + constant)); - if (qFuzzyCompare(1000 + leftHandSide, 1000 + constant)) + if ((leftHandSide == constant) || qFuzzyCompare(1000 + leftHandSide, 1000 + constant)) return true; switch (ratio) { @@ -118,6 +119,30 @@ struct QSimplexConstraint return false; } } + +#ifdef QT_DEBUG + QString toString() { + QString result; + result += QString::fromAscii("-- QSimplexConstraint %1 --").arg(int(this), 0, 16); + + QHash<QSimplexVariable *, qreal>::const_iterator iter; + for (iter = variables.constBegin(); iter != variables.constEnd(); ++iter) { + result += QString::fromAscii(" %1 x %2").arg(iter.value()).arg(int(iter.key()), 0, 16); + } + + switch (ratio) { + case LessOrEqual: + result += QString::fromAscii(" (less) <= %1").arg(constant); + break; + case MoreOrEqual: + result += QString::fromAscii(" (more) >= %1").arg(constant); + break; + default: + result += QString::fromAscii(" (eqal) == %1").arg(constant); + } + + return result; + } #endif }; @@ -129,7 +154,6 @@ public: qreal solveMin(); qreal solveMax(); - QList<QSimplexVariable *> constraintsVariables(); bool setConstraints(const QList<QSimplexConstraint *> constraints); void setObjective(QSimplexConstraint *objective); @@ -145,6 +169,7 @@ private: void combineRows(int toIndex, int fromIndex, qreal factor); // Simplex + bool simplifyConstraints(QList<QSimplexConstraint *> *constraints); int findPivotColumn(); int pivotRowForColumn(int column); void reducedRowEchelon(); @@ -168,11 +193,6 @@ private: qreal *matrix; }; -inline QList<QSimplexVariable *> QSimplex::constraintsVariables() -{ - return variables; -} - inline qreal QSimplex::valueAt(int rowIndex, int columnIndex) { return matrix[rowIndex * columns + columnIndex]; |