2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/internal/event/events/pan-gesture-processor.h>
25 #include <dali/public-api/actors/actor.h>
26 #include <dali/public-api/common/dali-common.h>
27 #include <dali/public-api/events/pan-gesture.h>
28 #include <dali/public-api/math/vector2.h>
29 #include <dali/integration-api/events/pan-gesture-event.h>
30 #include <dali/integration-api/gesture-manager.h>
31 #include <dali/integration-api/debug.h>
32 #include <dali/internal/event/common/stage-impl.h>
33 #include <dali/internal/event/render-tasks/render-task-impl.h>
34 #include <dali/internal/update/gestures/scene-graph-pan-gesture.h>
42 namespace // unnamed namespace
45 const unsigned long MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY( 50u );
48 * Functor which checks whether the specified actor is attached to the gesture detector.
49 * If the actor is attached, it also checks whether the number of touches of the current pan event
50 * are within the range of that expected by the detector.
51 * It returns true if it is no longer attached or the touches are out of range.
52 * This can be used in remove_if functions.
54 struct IsNotAttachedAndOutsideTouchesRangeFunctor
58 * @param[in] actor The actor to check whether it is attached.
59 * @param[in] touches The number of touches in the current pan event.
60 * @param[in] outsideRangeEmitters Reference to container where emitters outside of the touches range should be added.
62 IsNotAttachedAndOutsideTouchesRangeFunctor(Actor* actor, unsigned int touches, GestureDetectorContainer& outsideRangeEmitters)
63 : actorToCheck(actor),
64 numberOfTouches(touches),
65 outsideTouchesRangeEmitters(outsideRangeEmitters)
70 * Returns true if not attached, false if it is still attached.
71 * Additionally, checks if the number of touches has changed and stops sending the pan to a particular
72 * detector if it exceeds the range of that detector.
73 * @param[in] detector The detector to check.
74 * @return true, if not attached, false otherwise.
76 bool operator()(GestureDetector* detector) const
78 bool remove(!detector->IsAttached(*actorToCheck));
82 PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
84 // Ensure number of touch points is within the range of our emitter. If it isn't then remove
85 // this emitter and add it to the outsideTouchesRangeEmitters container
86 if ( (numberOfTouches < panDetector->GetMinimumTouchesRequired()) ||
87 (numberOfTouches > panDetector->GetMaximumTouchesRequired()) )
90 outsideTouchesRangeEmitters.push_back(detector);
97 Actor* actorToCheck; ///< The actor to check whether it is attached or not.
98 unsigned int numberOfTouches; ///< The number of touches in the pan event.
99 GestureDetectorContainer& outsideTouchesRangeEmitters; ///< Emitters that are outside of the range of current pan.
102 } // unnamed namespace
104 PanGestureProcessor::PanGestureProcessor( Stage& stage, Integration::GestureManager& gestureManager )
105 : GestureProcessor( Gesture::Pan ),
107 mGestureManager( gestureManager ),
109 mCurrentPanEmitters(),
110 mCurrentRenderTask(),
111 mPossiblePanPosition(),
112 mMinTouchesRequired( 1 ),
113 mMaxTouchesRequired( 1 ),
114 mCurrentPanEvent( NULL ),
115 mSceneObject( SceneGraph::PanGesture::New() ) // Create scene object to store pan information.
117 // Pass ownership to scene-graph
118 AddGestureMessage( mStage.GetUpdateManager(), mSceneObject );
121 PanGestureProcessor::~PanGestureProcessor()
123 if( Stage::IsInstalled() && ( mSceneObject != NULL ) )
125 RemoveGestureMessage( mStage.GetUpdateManager(), mSceneObject );
126 mSceneObject = NULL; // mSceneObject is about to be destroyed
130 void PanGestureProcessor::Process( const Integration::PanGestureEvent& panEvent )
132 switch( panEvent.state )
134 case Gesture::Possible:
136 mCurrentPanEmitters.clear();
139 HitTestAlgorithm::Results hitTestResults;
140 if( HitTest( mStage, panEvent.currentPosition, hitTestResults ) )
142 SetActor( &GetImplementation( hitTestResults.actor ) );
143 mPossiblePanPosition = panEvent.currentPosition;
149 case Gesture::Started:
151 if ( GetCurrentGesturedActor() )
153 // The pan gesture should only be sent to the gesture detector which first received it so that
154 // it can be told when the gesture ends as well.
156 HitTestAlgorithm::Results hitTestResults;
157 HitTest( mStage, mPossiblePanPosition, hitTestResults ); // Hit test original possible position...
159 if ( hitTestResults.actor && ( GetCurrentGesturedActor() == &GetImplementation( hitTestResults.actor ) ) )
161 // Record the current render-task for Screen->Actor coordinate conversions
162 mCurrentRenderTask = hitTestResults.renderTask;
164 // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
165 mCurrentPanEvent = &panEvent;
166 ProcessAndEmit( hitTestResults );
167 mCurrentPanEvent = NULL;
172 mCurrentPanEmitters.clear();
178 case Gesture::Continuing:
179 case Gesture::Finished:
180 case Gesture::Cancelled:
182 // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
183 // Check if actor is still touchable.
185 Actor* currentGesturedActor = GetCurrentGesturedActor();
186 if ( currentGesturedActor )
188 if ( currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask )
190 GestureDetectorContainer outsideTouchesRangeEmitters;
192 // Removes emitters that no longer have the actor attached
193 // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
194 GestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(),
195 IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters) );
196 mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
200 if ( !outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty() )
202 currentGesturedActor->ScreenToLocal( GetImplementation( mCurrentRenderTask ), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
204 // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
205 EmitPanSignal( currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, Gesture::Finished, mCurrentRenderTask);
206 EmitPanSignal( currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
209 if ( mCurrentPanEmitters.empty() )
211 // If we have no emitters attached then clear pan actor as well.
215 // Clear current gesture detectors if pan gesture has ended or been cancelled.
216 if ( ( panEvent.state == Gesture::Finished ) || ( panEvent.state == Gesture::Cancelled ) )
218 mCurrentPanEmitters.clear();
224 mCurrentPanEmitters.clear();
233 DALI_ABORT( "Incorrect state received from Integration layer: Clear\n" );
239 void PanGestureProcessor::AddGestureDetector( PanGestureDetector* gestureDetector )
241 bool firstRegistration(mGestureDetectors.empty());
243 mGestureDetectors.push_back(gestureDetector);
245 // Set the pan scene object on the gesture detector
246 gestureDetector->SetSceneObject( mSceneObject );
248 if (firstRegistration)
250 mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
251 mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
253 Integration::PanGestureRequest request;
254 request.minTouches = mMinTouchesRequired;
255 request.maxTouches = mMaxTouchesRequired;
256 mGestureManager.Register(request);
264 void PanGestureProcessor::RemoveGestureDetector( PanGestureDetector* gestureDetector )
266 if (!mCurrentPanEmitters.empty())
268 // Check if the removed detector was one that is currently being panned and remove it from emitters.
269 GestureDetectorContainer::iterator endIter = std::remove( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector );
270 mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
272 // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
273 if ( mCurrentPanEmitters.empty() )
279 // Find the detector...
280 PanGestureDetectorContainer::iterator endIter = std::remove( mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector );
281 DALI_ASSERT_DEBUG( endIter != mGestureDetectors.end() );
284 mGestureDetectors.erase(endIter, mGestureDetectors.end());
286 if (mGestureDetectors.empty())
288 Integration::GestureRequest request(Gesture::Pan);
289 mGestureManager.Unregister(request);
297 void PanGestureProcessor::GestureDetectorUpdated( PanGestureDetector* gestureDetector )
299 DALI_ASSERT_DEBUG(find(mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector) != mGestureDetectors.end());
304 void PanGestureProcessor::SetPanGestureProperties( const PanGesture& pan )
306 // If we are currently processing a pan gesture then just ignore
307 if ( mCurrentPanEmitters.empty() && mSceneObject )
309 // We update the scene object directly rather than sending a message.
310 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
311 mSceneObject->AddGesture( pan );
315 void PanGestureProcessor::EnableProfiling()
317 mSceneObject->EnableProfiling();
320 void PanGestureProcessor::SetPredictionMode(int mode)
323 || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES) )
325 mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
327 SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
328 mSceneObject->SetPredictionMode(modeEnum);
331 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
333 mSceneObject->SetPredictionAmount(amount);
336 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
338 mSceneObject->SetMaximumPredictionAmount(amount);
341 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
343 mSceneObject->SetMinimumPredictionAmount(amount);
346 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
348 mSceneObject->SetPredictionAmountAdjustment(amount);
351 void PanGestureProcessor::SetSmoothingMode(int mode)
354 || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES) )
356 mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
358 SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
359 mSceneObject->SetSmoothingMode(modeEnum);
362 void PanGestureProcessor::SetSmoothingAmount(float amount)
364 mSceneObject->SetSmoothingAmount(amount);
367 void PanGestureProcessor::UpdateDetection()
369 DALI_ASSERT_DEBUG(!mGestureDetectors.empty());
371 unsigned int minimumRequired = UINT_MAX;
372 unsigned int maximumRequired = 0;
374 for ( PanGestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
376 PanGestureDetector* detector(*iter);
380 unsigned int minimum = detector->GetMinimumTouchesRequired();
381 if (minimum < minimumRequired)
383 minimumRequired = minimum;
386 unsigned int maximum = detector->GetMaximumTouchesRequired();
387 if (maximum > maximumRequired)
389 maximumRequired = maximum;
394 if ( (minimumRequired != mMinTouchesRequired)||(maximumRequired != mMaxTouchesRequired) )
396 mMinTouchesRequired = minimumRequired;
397 mMaxTouchesRequired = maximumRequired;
399 Integration::PanGestureRequest request;
400 request.minTouches = mMinTouchesRequired;
401 request.maxTouches = mMaxTouchesRequired;
402 mGestureManager.Update(request);
406 void PanGestureProcessor::EmitPanSignal( Actor* actor,
407 const GestureDetectorContainer& gestureDetectors,
408 const Integration::PanGestureEvent& panEvent,
409 Vector2 localCurrent,
410 Gesture::State state,
411 Dali::RenderTask renderTask )
413 if ( actor && !gestureDetectors.empty() )
415 PanGesture pan(state);
416 pan.time = panEvent.time;
418 pan.numberOfTouches = panEvent.numberOfTouches;
419 pan.screenPosition = panEvent.currentPosition;
420 pan.position = localCurrent;
422 RenderTask& renderTaskImpl( GetImplementation( renderTask ) );
424 Vector2 localPrevious;
425 actor->ScreenToLocal( renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y );
427 pan.displacement = localCurrent - localPrevious;
428 Vector2 previousPos( panEvent.previousPosition );
429 if ( state == Gesture::Started )
431 previousPos = mPossiblePanPosition;
434 pan.screenDisplacement = panEvent.currentPosition - previousPos;
436 // Avoid dividing by 0
437 if ( panEvent.timeDelta > 0 )
439 pan.velocity.x = pan.displacement.x / panEvent.timeDelta;
440 pan.velocity.y = pan.displacement.y / panEvent.timeDelta;
442 pan.screenVelocity.x = pan.screenDisplacement.x / panEvent.timeDelta;
443 pan.screenVelocity.y = pan.screenDisplacement.y / panEvent.timeDelta;
446 // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
447 // so we should use the last recorded velocity instead in this scenario.
448 if ( ( state == Gesture::Finished ) && ( pan.screenVelocity == Vector2::ZERO ) &&
449 ( panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY ) )
451 pan.velocity = mLastVelocity;
452 pan.screenVelocity = mLastScreenVelocity;
456 // Store the current velocity for future iterations.
457 mLastVelocity = pan.velocity;
458 mLastScreenVelocity = pan.screenVelocity;
463 // We update the scene object directly rather than sending a message.
464 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
465 mSceneObject->AddGesture( pan );
468 Dali::Actor actorHandle( actor );
469 const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
470 for ( GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter )
472 static_cast< PanGestureDetector* >( *iter )->EmitPanGestureSignal( actorHandle, pan );
477 void PanGestureProcessor::OnGesturedActorStageDisconnection()
479 mCurrentPanEmitters.clear();
482 bool PanGestureProcessor::CheckGestureDetector( GestureDetector* detector, Actor* actor )
484 DALI_ASSERT_DEBUG( mCurrentPanEvent );
486 bool retVal( false );
487 PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
489 if ( ( mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired() ) &&
490 ( mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired() ) )
492 // Check if the detector requires directional panning.
493 if ( panDetector->RequiresDirectionalPan() && mCurrentRenderTask )
495 // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
496 // the detector's criteria.
497 RenderTask& renderTaskImpl( GetImplementation( mCurrentRenderTask ) );
499 Vector2 startPosition, currentPosition;
500 actor->ScreenToLocal( renderTaskImpl, startPosition.x, startPosition.y, mPossiblePanPosition.x, mPossiblePanPosition.y );
501 actor->ScreenToLocal( renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
502 Vector2 displacement( currentPosition - startPosition );
504 Radian angle( atan( displacement.y / displacement.x ) );
506 /////////////////////////////
509 // Q3 (-,-) | Q4 (+,-) //
511 // ----------------- +x //
513 // Q2 (-,+) | Q1 (+,+) //
517 /////////////////////////////
519 // Quadrant 2: 180 degrees + angle
520 // Quadrant 3: angle - 180 degrees
522 /////////////////////////////
524 if ( displacement.x < 0.0f )
526 if ( displacement.y >= 0.0f )
529 angle.radian += Math::PI;
534 angle.radian -= Math::PI;
538 if ( panDetector->CheckAngleAllowed( angle ) )
545 // Directional panning not required so we can use this actor and gesture detector.
552 void PanGestureProcessor::EmitGestureSignal( Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates )
554 DALI_ASSERT_DEBUG ( mCurrentPanEvent );
556 mCurrentPanEmitters.clear();
559 actor->ScreenToLocal( GetImplementation(mCurrentRenderTask), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
561 EmitPanSignal( actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask );
563 if ( actor->OnStage() )
565 mCurrentPanEmitters = gestureDetectors;
570 } // namespace Internal