2 * Copyright (c) 2017 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, SceneGraph::UpdateManager& updateManager )
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; scene object lives for the lifecycle of UpdateManager
118 updateManager.SetPanGestureProcessor( mSceneObject );
121 PanGestureProcessor::~PanGestureProcessor()
123 mSceneObject = NULL; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
126 void PanGestureProcessor::Process( const Integration::PanGestureEvent& panEvent )
128 switch( panEvent.state )
130 case Gesture::Possible:
132 mCurrentPanEmitters.clear();
135 HitTestAlgorithm::Results hitTestResults;
136 if( HitTest( mStage, panEvent.currentPosition, hitTestResults ) )
138 SetActor( &GetImplementation( hitTestResults.actor ) );
139 mPossiblePanPosition = panEvent.currentPosition;
145 case Gesture::Started:
147 if ( GetCurrentGesturedActor() )
149 // The pan gesture should only be sent to the gesture detector which first received it so that
150 // it can be told when the gesture ends as well.
152 HitTestAlgorithm::Results hitTestResults;
153 HitTest( mStage, mPossiblePanPosition, hitTestResults ); // Hit test original possible position...
155 if ( hitTestResults.actor && ( GetCurrentGesturedActor() == &GetImplementation( hitTestResults.actor ) ) )
157 // Record the current render-task for Screen->Actor coordinate conversions
158 mCurrentRenderTask = hitTestResults.renderTask;
160 // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
161 mCurrentPanEvent = &panEvent;
162 ProcessAndEmit( hitTestResults );
163 mCurrentPanEvent = NULL;
168 mCurrentPanEmitters.clear();
174 case Gesture::Continuing:
175 case Gesture::Finished:
176 case Gesture::Cancelled:
178 // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
179 // Check if actor is still touchable.
181 Actor* currentGesturedActor = GetCurrentGesturedActor();
182 if ( currentGesturedActor )
184 if ( currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask )
186 GestureDetectorContainer outsideTouchesRangeEmitters;
188 // Removes emitters that no longer have the actor attached
189 // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
190 GestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(),
191 IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters) );
192 mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
196 if ( !outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty() )
198 currentGesturedActor->ScreenToLocal( GetImplementation( mCurrentRenderTask ), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
200 // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
201 EmitPanSignal( currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, Gesture::Finished, mCurrentRenderTask);
202 EmitPanSignal( currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
205 if ( mCurrentPanEmitters.empty() )
207 // If we have no emitters attached then clear pan actor as well.
211 // Clear current gesture detectors if pan gesture has ended or been cancelled.
212 if ( ( panEvent.state == Gesture::Finished ) || ( panEvent.state == Gesture::Cancelled ) )
214 mCurrentPanEmitters.clear();
220 mCurrentPanEmitters.clear();
229 DALI_ABORT( "Incorrect state received from Integration layer: Clear\n" );
235 void PanGestureProcessor::AddGestureDetector( PanGestureDetector* gestureDetector )
237 bool firstRegistration(mGestureDetectors.empty());
239 mGestureDetectors.push_back(gestureDetector);
241 // Set the pan scene object on the gesture detector
242 gestureDetector->SetSceneObject( mSceneObject );
244 if (firstRegistration)
246 mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
247 mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
249 Integration::PanGestureRequest request;
250 request.minTouches = mMinTouchesRequired;
251 request.maxTouches = mMaxTouchesRequired;
252 mGestureManager.Register(request);
260 void PanGestureProcessor::RemoveGestureDetector( PanGestureDetector* gestureDetector )
262 if (!mCurrentPanEmitters.empty())
264 // Check if the removed detector was one that is currently being panned and remove it from emitters.
265 GestureDetectorContainer::iterator endIter = std::remove( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector );
266 mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
268 // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
269 if ( mCurrentPanEmitters.empty() )
275 // Find the detector...
276 PanGestureDetectorContainer::iterator endIter = std::remove( mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector );
277 DALI_ASSERT_DEBUG( endIter != mGestureDetectors.end() );
280 mGestureDetectors.erase(endIter, mGestureDetectors.end());
282 if (mGestureDetectors.empty())
284 Integration::GestureRequest request(Gesture::Pan);
285 mGestureManager.Unregister(request);
293 void PanGestureProcessor::GestureDetectorUpdated( PanGestureDetector* gestureDetector )
295 DALI_ASSERT_DEBUG(find(mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector) != mGestureDetectors.end());
300 void PanGestureProcessor::SetPanGestureProperties( const PanGesture& pan )
302 // If we are currently processing a pan gesture then just ignore
303 if ( mCurrentPanEmitters.empty() && mSceneObject )
305 // We update the scene object directly rather than sending a message.
306 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
307 mSceneObject->AddGesture( pan );
311 void PanGestureProcessor::EnableProfiling()
313 mSceneObject->EnableProfiling();
316 void PanGestureProcessor::SetPredictionMode(int mode)
319 || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES) )
321 mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
323 SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
324 mSceneObject->SetPredictionMode(modeEnum);
327 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
329 mSceneObject->SetPredictionAmount(amount);
332 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
334 mSceneObject->SetMaximumPredictionAmount(amount);
337 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
339 mSceneObject->SetMinimumPredictionAmount(amount);
342 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
344 mSceneObject->SetPredictionAmountAdjustment(amount);
347 void PanGestureProcessor::SetSmoothingMode(int mode)
350 || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES) )
352 mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
354 SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
355 mSceneObject->SetSmoothingMode(modeEnum);
358 void PanGestureProcessor::SetSmoothingAmount(float amount)
360 mSceneObject->SetSmoothingAmount(amount);
363 void PanGestureProcessor::SetUseActualTimes( bool value )
365 mSceneObject->SetUseActualTimes( value );
368 void PanGestureProcessor::SetInterpolationTimeRange( int value )
370 mSceneObject->SetInterpolationTimeRange( value );
373 void PanGestureProcessor::SetScalarOnlyPredictionEnabled( bool value )
375 mSceneObject->SetScalarOnlyPredictionEnabled( value );
378 void PanGestureProcessor::SetTwoPointPredictionEnabled( bool value )
380 mSceneObject->SetTwoPointPredictionEnabled( value );
383 void PanGestureProcessor::SetTwoPointInterpolatePastTime( int value )
385 mSceneObject->SetTwoPointInterpolatePastTime( value );
388 void PanGestureProcessor::SetTwoPointVelocityBias( float value )
390 mSceneObject->SetTwoPointVelocityBias( value );
393 void PanGestureProcessor::SetTwoPointAccelerationBias( float value )
395 mSceneObject->SetTwoPointAccelerationBias( value );
398 void PanGestureProcessor::SetMultitapSmoothingRange( int value )
400 mSceneObject->SetMultitapSmoothingRange( value );
403 void PanGestureProcessor::UpdateDetection()
405 DALI_ASSERT_DEBUG(!mGestureDetectors.empty());
407 unsigned int minimumRequired = UINT_MAX;
408 unsigned int maximumRequired = 0;
410 for ( PanGestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
412 PanGestureDetector* detector(*iter);
416 unsigned int minimum = detector->GetMinimumTouchesRequired();
417 if (minimum < minimumRequired)
419 minimumRequired = minimum;
422 unsigned int maximum = detector->GetMaximumTouchesRequired();
423 if (maximum > maximumRequired)
425 maximumRequired = maximum;
430 if ( (minimumRequired != mMinTouchesRequired)||(maximumRequired != mMaxTouchesRequired) )
432 mMinTouchesRequired = minimumRequired;
433 mMaxTouchesRequired = maximumRequired;
435 Integration::PanGestureRequest request;
436 request.minTouches = mMinTouchesRequired;
437 request.maxTouches = mMaxTouchesRequired;
438 mGestureManager.Update(request);
442 void PanGestureProcessor::EmitPanSignal( Actor* actor,
443 const GestureDetectorContainer& gestureDetectors,
444 const Integration::PanGestureEvent& panEvent,
445 Vector2 localCurrent,
446 Gesture::State state,
447 Dali::RenderTask renderTask )
449 if ( actor && !gestureDetectors.empty() )
451 PanGesture pan(state);
452 pan.time = panEvent.time;
454 pan.numberOfTouches = panEvent.numberOfTouches;
455 pan.screenPosition = panEvent.currentPosition;
456 pan.position = localCurrent;
458 RenderTask& renderTaskImpl( GetImplementation( renderTask ) );
460 Vector2 localPrevious;
461 actor->ScreenToLocal( renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y );
463 pan.displacement = localCurrent - localPrevious;
464 Vector2 previousPos( panEvent.previousPosition );
465 if ( state == Gesture::Started )
467 previousPos = mPossiblePanPosition;
470 pan.screenDisplacement = panEvent.currentPosition - previousPos;
472 // Avoid dividing by 0
473 if ( panEvent.timeDelta > 0 )
475 pan.velocity.x = pan.displacement.x / panEvent.timeDelta;
476 pan.velocity.y = pan.displacement.y / panEvent.timeDelta;
478 pan.screenVelocity.x = pan.screenDisplacement.x / panEvent.timeDelta;
479 pan.screenVelocity.y = pan.screenDisplacement.y / panEvent.timeDelta;
482 // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
483 // so we should use the last recorded velocity instead in this scenario.
484 if ( ( state == Gesture::Finished ) && ( pan.screenVelocity == Vector2::ZERO ) &&
485 ( panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY ) )
487 pan.velocity = mLastVelocity;
488 pan.screenVelocity = mLastScreenVelocity;
492 // Store the current velocity for future iterations.
493 mLastVelocity = pan.velocity;
494 mLastScreenVelocity = pan.screenVelocity;
499 // We update the scene object directly rather than sending a message.
500 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
501 mSceneObject->AddGesture( pan );
504 Dali::Actor actorHandle( actor );
505 const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
506 for ( GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter )
508 static_cast< PanGestureDetector* >( *iter )->EmitPanGestureSignal( actorHandle, pan );
513 void PanGestureProcessor::OnGesturedActorStageDisconnection()
515 mCurrentPanEmitters.clear();
518 bool PanGestureProcessor::CheckGestureDetector( GestureDetector* detector, Actor* actor )
520 DALI_ASSERT_DEBUG( mCurrentPanEvent );
522 bool retVal( false );
523 PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
525 if ( ( mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired() ) &&
526 ( mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired() ) )
528 // Check if the detector requires directional panning.
529 if ( panDetector->RequiresDirectionalPan() && mCurrentRenderTask )
531 // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
532 // the detector's criteria.
533 RenderTask& renderTaskImpl( GetImplementation( mCurrentRenderTask ) );
535 Vector2 startPosition, currentPosition;
536 actor->ScreenToLocal( renderTaskImpl, startPosition.x, startPosition.y, mPossiblePanPosition.x, mPossiblePanPosition.y );
537 actor->ScreenToLocal( renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
538 Vector2 displacement( currentPosition - startPosition );
540 Radian angle( atan( displacement.y / displacement.x ) );
542 /////////////////////////////
545 // Q3 (-,-) | Q4 (+,-) //
547 // ----------------- +x //
549 // Q2 (-,+) | Q1 (+,+) //
553 /////////////////////////////
555 // Quadrant 2: 180 degrees + angle
556 // Quadrant 3: angle - 180 degrees
558 /////////////////////////////
560 if ( displacement.x < 0.0f )
562 if ( displacement.y >= 0.0f )
565 angle.radian += Math::PI;
570 angle.radian -= Math::PI;
574 if ( panDetector->CheckAngleAllowed( angle ) )
581 // Directional panning not required so we can use this actor and gesture detector.
588 void PanGestureProcessor::EmitGestureSignal( Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates )
590 DALI_ASSERT_DEBUG ( mCurrentPanEvent );
592 mCurrentPanEmitters.clear();
595 actor->ScreenToLocal( GetImplementation(mCurrentRenderTask), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
597 EmitPanSignal( actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask );
599 if ( actor->OnStage() )
601 mCurrentPanEmitters = gestureDetectors;
606 } // namespace Internal