2 * Copyright (c) 2019 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/pan-gesture-processor.h>
21 #if defined(DEBUG_ENABLED)
29 #include <dali/public-api/actors/actor.h>
30 #include <dali/public-api/common/dali-common.h>
31 #include <dali/public-api/events/pan-gesture.h>
32 #include <dali/public-api/math/vector2.h>
33 #include <dali/internal/event/events/pan-gesture/pan-gesture-event.h>
34 #include <dali/integration-api/debug.h>
35 #include <dali/internal/event/common/scene-impl.h>
36 #include <dali/internal/event/render-tasks/render-task-impl.h>
37 #include <dali/internal/update/gestures/scene-graph-pan-gesture.h>
38 #include <dali/internal/event/events/multi-point-event-util.h>
39 #include <dali/internal/event/events/pan-gesture/pan-gesture-recognizer.h>
40 #include <dali/internal/event/events/gesture-requests.h>
48 namespace // unnamed namespace
51 #if defined(DEBUG_ENABLED)
52 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_PAN_PROCESSOR" );
54 const char * GESTURE_STATES[ 6 ] =
64 #endif // defined(DEBUG_ENABLED)
66 const unsigned long MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY( 50u );
69 * Functor which checks whether the specified actor is attached to the gesture detector.
70 * If the actor is attached, it also checks whether the number of touches of the current pan event
71 * are within the range of that expected by the detector.
72 * It returns true if it is no longer attached or the touches are out of range.
73 * This can be used in remove_if functions.
75 struct IsNotAttachedAndOutsideTouchesRangeFunctor
79 * @param[in] actor The actor to check whether it is attached.
80 * @param[in] touches The number of touches in the current pan event.
81 * @param[in] outsideRangeEmitters Reference to container where emitters outside of the touches range should be added.
83 IsNotAttachedAndOutsideTouchesRangeFunctor(Actor* actor, unsigned int touches, GestureDetectorContainer& outsideRangeEmitters)
84 : actorToCheck(actor),
85 numberOfTouches(touches),
86 outsideTouchesRangeEmitters(outsideRangeEmitters)
91 * Returns true if not attached, false if it is still attached.
92 * Additionally, checks if the number of touches has changed and stops sending the pan to a particular
93 * detector if it exceeds the range of that detector.
94 * @param[in] detector The detector to check.
95 * @return true, if not attached, false otherwise.
97 bool operator()(GestureDetector* detector) const
99 bool remove(!detector->IsAttached(*actorToCheck));
103 PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
105 // Ensure number of touch points is within the range of our emitter. If it isn't then remove
106 // this emitter and add it to the outsideTouchesRangeEmitters container
107 if ( (numberOfTouches < panDetector->GetMinimumTouchesRequired()) ||
108 (numberOfTouches > panDetector->GetMaximumTouchesRequired()) )
111 outsideTouchesRangeEmitters.push_back(detector);
118 Actor* actorToCheck; ///< The actor to check whether it is attached or not.
119 unsigned int numberOfTouches; ///< The number of touches in the pan event.
120 GestureDetectorContainer& outsideTouchesRangeEmitters; ///< Emitters that are outside of the range of current pan.
123 } // unnamed namespace
125 PanGestureProcessor::PanGestureProcessor( SceneGraph::UpdateManager& updateManager )
126 : GestureProcessor( Gesture::Pan ),
127 mPanGestureDetectors(),
128 mCurrentPanEmitters(),
129 mCurrentRenderTask(),
130 mPossiblePanPosition(),
131 mMinTouchesRequired( 1 ),
132 mMaxTouchesRequired( 1 ),
133 mCurrentPanEvent( nullptr ),
134 mSceneObject( SceneGraph::PanGesture::New() ) // Create scene object to store pan information.
136 // Pass ownership to scene-graph; scene object lives for the lifecycle of UpdateManager
137 updateManager.SetPanGestureProcessor( mSceneObject );
140 PanGestureProcessor::~PanGestureProcessor()
142 mSceneObject = nullptr; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
145 void PanGestureProcessor::Process( Scene& scene, const PanGestureEvent& panEvent )
147 #if defined(DEBUG_ENABLED)
148 DALI_LOG_TRACE_METHOD( gLogFilter );
150 DALI_LOG_INFO( gLogFilter, Debug::General, " Pan Event\n");
151 DALI_LOG_INFO( gLogFilter, Debug::General, " State: %s Touches: %d Time: %d TimeDelta: %d\n",
152 GESTURE_STATES[panEvent.state], panEvent.numberOfTouches, panEvent.time, panEvent.timeDelta);
153 DALI_LOG_INFO( gLogFilter, Debug::General, " Positions: Current: (%.0f, %.0f), Previous: (%.0f, %.0f)\n",
154 panEvent.currentPosition.x, panEvent.currentPosition.y, panEvent.previousPosition.x, panEvent.previousPosition.y);
157 switch( panEvent.state )
159 case Gesture::Possible:
161 mCurrentPanEmitters.clear();
164 HitTestAlgorithm::Results hitTestResults;
165 if( HitTest( scene, panEvent.currentPosition, hitTestResults ) )
167 SetActor( &GetImplementation( hitTestResults.actor ) );
168 mPossiblePanPosition = panEvent.currentPosition;
173 case Gesture::Started:
175 // Requires a core update
178 // The pan gesture should only be sent to the gesture detector which first received it so that
179 // it can be told when the gesture ends as well.
181 HitTestAlgorithm::Results hitTestResults;
182 HitTest( scene, panEvent.previousPosition, hitTestResults ); // Hit Test previous position
184 if ( hitTestResults.actor )
186 // If the current hit actor is different from the one we touched down on then set accordingly & update initial pan position
187 if( &GetImplementation( hitTestResults.actor ) != GetCurrentGesturedActor() )
189 mPossiblePanPosition = panEvent.previousPosition;
190 SetActor( &GetImplementation( hitTestResults.actor ) );
193 // Record the current render-task for Screen->Actor coordinate conversions
194 mCurrentRenderTask = hitTestResults.renderTask;
196 // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
197 mCurrentPanEvent = &panEvent;
198 ProcessAndEmit( hitTestResults );
199 mCurrentPanEvent = nullptr;
204 mCurrentPanEmitters.clear();
209 case Gesture::Continuing:
211 // Requires a core update
214 // No break, Fallthrough
215 case Gesture::Finished:
216 case Gesture::Cancelled:
218 // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
219 // Check if actor is still touchable.
221 Actor* currentGesturedActor = GetCurrentGesturedActor();
222 if ( currentGesturedActor )
224 if ( currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask )
226 GestureDetectorContainer outsideTouchesRangeEmitters;
228 // Removes emitters that no longer have the actor attached
229 // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
230 GestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(),
231 IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters) );
232 mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
236 if ( !outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty() )
238 currentGesturedActor->ScreenToLocal( *mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
240 // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
241 EmitPanSignal( currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, Gesture::Finished, mCurrentRenderTask);
242 EmitPanSignal( currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
245 if ( mCurrentPanEmitters.empty() )
247 // If we have no emitters attached then clear pan actor as well.
251 // Clear current gesture detectors if pan gesture has ended or been cancelled.
252 if ( ( panEvent.state == Gesture::Finished ) || ( panEvent.state == Gesture::Cancelled ) )
254 mCurrentPanEmitters.clear();
260 mCurrentPanEmitters.clear();
269 DALI_ABORT( "Incorrect state received from Integration layer: Clear\n" );
275 void PanGestureProcessor::AddGestureDetector( PanGestureDetector* gestureDetector, Scene& scene, int32_t minDistance, int32_t minPanEvents )
277 bool firstRegistration(mPanGestureDetectors.empty());
279 mPanGestureDetectors.push_back(gestureDetector);
281 if (firstRegistration)
283 mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
284 mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
286 PanGestureRequest request;
287 request.minTouches = mMinTouchesRequired;
288 request.maxTouches = mMaxTouchesRequired;
290 Size size = scene.GetSize();
291 mGestureRecognizer = new PanGestureRecognizer(*this, Vector2(size.width, size.height), static_cast<const PanGestureRequest&>(request), minDistance, minPanEvents);
299 void PanGestureProcessor::RemoveGestureDetector( PanGestureDetector* gestureDetector )
301 if (!mCurrentPanEmitters.empty())
303 // Check if the removed detector was one that is currently being panned and remove it from emitters.
304 GestureDetectorContainer::iterator endIter = std::remove( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector );
305 mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
307 // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
308 if ( mCurrentPanEmitters.empty() )
314 // Find the detector...
315 PanGestureDetectorContainer::iterator endIter = std::remove( mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector );
316 DALI_ASSERT_DEBUG( endIter != mPanGestureDetectors.end() );
319 mPanGestureDetectors.erase(endIter, mPanGestureDetectors.end());
321 if (mPanGestureDetectors.empty())
323 mGestureRecognizer.Detach();
331 void PanGestureProcessor::GestureDetectorUpdated( PanGestureDetector* gestureDetector )
333 DALI_ASSERT_DEBUG(find(mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector) != mPanGestureDetectors.end());
338 bool PanGestureProcessor::SetPanGestureProperties( const PanGesture& pan )
340 // If we are currently processing a pan gesture then just ignore
341 if ( mCurrentPanEmitters.empty() && mSceneObject )
343 // We update the scene object directly rather than sending a message.
344 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
345 mSceneObject->AddGesture( pan );
347 if( Gesture::Started == pan.state || Gesture::Continuing == pan.state )
356 void PanGestureProcessor::EnableProfiling()
358 mSceneObject->EnableProfiling();
361 void PanGestureProcessor::SetPredictionMode(int mode)
364 || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES) )
366 mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
368 SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
369 mSceneObject->SetPredictionMode(modeEnum);
372 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
374 mSceneObject->SetPredictionAmount(amount);
377 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
379 mSceneObject->SetMaximumPredictionAmount(amount);
382 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
384 mSceneObject->SetMinimumPredictionAmount(amount);
387 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
389 mSceneObject->SetPredictionAmountAdjustment(amount);
392 void PanGestureProcessor::SetSmoothingMode(int mode)
395 || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES) )
397 mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
399 SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
400 mSceneObject->SetSmoothingMode(modeEnum);
403 void PanGestureProcessor::SetSmoothingAmount(float amount)
405 mSceneObject->SetSmoothingAmount(amount);
408 void PanGestureProcessor::SetUseActualTimes( bool value )
410 mSceneObject->SetUseActualTimes( value );
413 void PanGestureProcessor::SetInterpolationTimeRange( int value )
415 mSceneObject->SetInterpolationTimeRange( value );
418 void PanGestureProcessor::SetScalarOnlyPredictionEnabled( bool value )
420 mSceneObject->SetScalarOnlyPredictionEnabled( value );
423 void PanGestureProcessor::SetTwoPointPredictionEnabled( bool value )
425 mSceneObject->SetTwoPointPredictionEnabled( value );
428 void PanGestureProcessor::SetTwoPointInterpolatePastTime( int value )
430 mSceneObject->SetTwoPointInterpolatePastTime( value );
433 void PanGestureProcessor::SetTwoPointVelocityBias( float value )
435 mSceneObject->SetTwoPointVelocityBias( value );
438 void PanGestureProcessor::SetTwoPointAccelerationBias( float value )
440 mSceneObject->SetTwoPointAccelerationBias( value );
443 void PanGestureProcessor::SetMultitapSmoothingRange( int value )
445 mSceneObject->SetMultitapSmoothingRange( value );
448 const SceneGraph::PanGesture& PanGestureProcessor::GetSceneObject() const
450 return *mSceneObject;
453 void PanGestureProcessor::UpdateDetection()
455 DALI_ASSERT_DEBUG(!mPanGestureDetectors.empty());
457 unsigned int minimumRequired = UINT_MAX;
458 unsigned int maximumRequired = 0;
460 for ( PanGestureDetectorContainer::iterator iter = mPanGestureDetectors.begin(), endIter = mPanGestureDetectors.end(); iter != endIter; ++iter )
462 PanGestureDetector* detector(*iter);
466 unsigned int minimum = detector->GetMinimumTouchesRequired();
467 if (minimum < minimumRequired)
469 minimumRequired = minimum;
472 unsigned int maximum = detector->GetMaximumTouchesRequired();
473 if (maximum > maximumRequired)
475 maximumRequired = maximum;
480 if ( (minimumRequired != mMinTouchesRequired)||(maximumRequired != mMaxTouchesRequired) )
482 mMinTouchesRequired = minimumRequired;
483 mMaxTouchesRequired = maximumRequired;
485 PanGestureRequest request;
486 request.minTouches = mMinTouchesRequired;
487 request.maxTouches = mMaxTouchesRequired;
488 mGestureRecognizer->Update(request);
492 void PanGestureProcessor::EmitPanSignal( Actor* actor,
493 const GestureDetectorContainer& gestureDetectors,
494 const PanGestureEvent& panEvent,
495 Vector2 localCurrent,
496 Gesture::State state,
497 RenderTaskPtr renderTask )
499 if ( actor && !gestureDetectors.empty() )
501 PanGesture pan(state);
502 pan.time = panEvent.time;
504 pan.numberOfTouches = panEvent.numberOfTouches;
505 pan.screenPosition = panEvent.currentPosition;
506 pan.position = localCurrent;
508 RenderTask& renderTaskImpl( *renderTask.Get() );
510 Vector2 localPrevious;
511 actor->ScreenToLocal( renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y );
513 pan.displacement = localCurrent - localPrevious;
514 Vector2 previousPos( panEvent.previousPosition );
515 if ( state == Gesture::Started )
517 previousPos = mPossiblePanPosition;
520 pan.screenDisplacement = panEvent.currentPosition - previousPos;
522 // Avoid dividing by 0
523 if ( panEvent.timeDelta > 0 )
525 pan.velocity.x = pan.displacement.x / static_cast<float>( panEvent.timeDelta );
526 pan.velocity.y = pan.displacement.y / static_cast<float>( panEvent.timeDelta );
528 pan.screenVelocity.x = pan.screenDisplacement.x / static_cast<float>( panEvent.timeDelta );
529 pan.screenVelocity.y = pan.screenDisplacement.y / static_cast<float>( panEvent.timeDelta );
532 // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
533 // so we should use the last recorded velocity instead in this scenario.
534 if ( ( state == Gesture::Finished ) && ( pan.screenVelocity == Vector2::ZERO ) &&
535 ( panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY ) )
537 pan.velocity = mLastVelocity;
538 pan.screenVelocity = mLastScreenVelocity;
542 // Store the current velocity for future iterations.
543 mLastVelocity = pan.velocity;
544 mLastScreenVelocity = pan.screenVelocity;
549 // We update the scene object directly rather than sending a message.
550 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
551 mSceneObject->AddGesture( pan );
554 Dali::Actor actorHandle( actor );
556 const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
557 for ( GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter )
559 static_cast< PanGestureDetector* >( *iter )->EmitPanGestureSignal( actorHandle, pan );
564 void PanGestureProcessor::OnGesturedActorStageDisconnection()
566 mCurrentPanEmitters.clear();
569 bool PanGestureProcessor::CheckGestureDetector( GestureDetector* detector, Actor* actor )
571 DALI_ASSERT_DEBUG( mCurrentPanEvent );
573 bool retVal( false );
574 PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
576 if ( ( mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired() ) &&
577 ( mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired() ) )
579 // Check if the detector requires directional panning.
580 if ( panDetector->RequiresDirectionalPan() && mCurrentRenderTask )
582 // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
583 // the detector's criteria.
584 RenderTask& renderTaskImpl = *mCurrentRenderTask.Get();
586 Vector2 startPosition, currentPosition;
587 actor->ScreenToLocal( renderTaskImpl, startPosition.x, startPosition.y, mPossiblePanPosition.x, mPossiblePanPosition.y );
588 actor->ScreenToLocal( renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
589 Vector2 displacement( currentPosition - startPosition );
591 Radian angle( atanf( displacement.y / displacement.x ) );
593 /////////////////////////////
596 // Q3 (-,-) | Q4 (+,-) //
598 // ----------------- +x //
600 // Q2 (-,+) | Q1 (+,+) //
604 /////////////////////////////
606 // Quadrant 2: 180 degrees + angle
607 // Quadrant 3: angle - 180 degrees
609 /////////////////////////////
611 if ( displacement.x < 0.0f )
613 if ( displacement.y >= 0.0f )
616 angle.radian += Math::PI;
621 angle.radian -= Math::PI;
625 if ( panDetector->CheckAngleAllowed( angle ) )
632 // Directional panning not required so we can use this actor and gesture detector.
639 void PanGestureProcessor::EmitGestureSignal( Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates )
641 DALI_ASSERT_DEBUG ( mCurrentPanEvent );
643 mCurrentPanEmitters.clear();
646 actor->ScreenToLocal( *mCurrentRenderTask.Get(), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
648 EmitPanSignal( actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask );
650 if ( actor->OnStage() )
652 mCurrentPanEmitters = gestureDetectors;
657 } // namespace Internal