2 * Copyright (c) 2022 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/integration-api/debug.h>
30 #include <dali/internal/event/common/scene-impl.h>
31 #include <dali/internal/event/events/gesture-requests.h>
32 #include <dali/internal/event/events/multi-point-event-util.h>
33 #include <dali/internal/event/events/pan-gesture/pan-gesture-event.h>
34 #include <dali/internal/event/events/pan-gesture/pan-gesture-impl.h>
35 #include <dali/internal/event/events/pan-gesture/pan-gesture-recognizer.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/update/manager/update-manager.h>
39 #include <dali/public-api/actors/actor.h>
40 #include <dali/public-api/common/dali-common.h>
41 #include <dali/public-api/events/pan-gesture.h>
42 #include <dali/public-api/math/vector2.h>
48 namespace // unnamed namespace
50 #if defined(DEBUG_ENABLED)
51 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_PAN_PROCESSOR");
53 const char* GESTURE_STATES[6] =
62 #endif // defined(DEBUG_ENABLED)
64 const unsigned long MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY(50u);
67 * Functor which checks whether the specified actor is attached to the gesture detector.
68 * If the actor is attached, it also checks whether the number of touches of the current pan event
69 * are within the range of that expected by the detector.
70 * It returns true if it is no longer attached or the touches are out of range.
71 * This can be used in remove_if functions.
73 struct IsNotAttachedAndOutsideTouchesRangeFunctor
77 * @param[in] actor The actor to check whether it is attached.
78 * @param[in] touches The number of touches in the current pan event.
79 * @param[in] outsideRangeEmitters Reference to container where emitters outside of the touches range should be added.
81 IsNotAttachedAndOutsideTouchesRangeFunctor(Actor* actor, unsigned int touches, GestureDetectorContainer& outsideRangeEmitters)
82 : actorToCheck(actor),
83 numberOfTouches(touches),
84 outsideTouchesRangeEmitters(outsideRangeEmitters)
89 * Returns true if not attached, false if it is still attached.
90 * Additionally, checks if the number of touches has changed and stops sending the pan to a particular
91 * detector if it exceeds the range of that detector.
92 * @param[in] detector The detector to check.
93 * @return true, if not attached, false otherwise.
95 bool operator()(GestureDetector* detector) const
97 bool remove(!detector->IsAttached(*actorToCheck));
101 PanGestureDetector* panDetector(static_cast<PanGestureDetector*>(detector));
103 // Ensure number of touch points is within the range of our emitter. If it isn't then remove
104 // this emitter and add it to the outsideTouchesRangeEmitters container
105 if((numberOfTouches < panDetector->GetMinimumTouchesRequired()) ||
106 (numberOfTouches > panDetector->GetMaximumTouchesRequired()))
109 outsideTouchesRangeEmitters.push_back(detector);
116 Actor* actorToCheck; ///< The actor to check whether it is attached or not.
117 unsigned int numberOfTouches; ///< The number of touches in the pan event.
118 GestureDetectorContainer& outsideTouchesRangeEmitters; ///< Emitters that are outside of the range of current pan.
121 } // unnamed namespace
123 PanGestureProcessor::PanGestureProcessor(SceneGraph::UpdateManager& updateManager)
124 : GestureProcessor(GestureType::PAN),
125 mPanGestureDetectors(),
126 mCurrentPanEmitters(),
127 mCurrentRenderTask(),
128 mPossiblePanPosition(),
129 mMinTouchesRequired(1),
130 mMaxTouchesRequired(1),
131 mCurrentPanEvent(nullptr),
132 mSceneObject(SceneGraph::PanGesture::New()) // Create scene object to store pan information.
134 // Pass ownership to scene-graph; scene object lives for the lifecycle of UpdateManager
135 updateManager.SetPanGestureProcessor(mSceneObject);
138 PanGestureProcessor::~PanGestureProcessor()
140 mSceneObject = nullptr; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
143 void PanGestureProcessor::Process(Scene& scene, const PanGestureEvent& panEvent)
145 #if defined(DEBUG_ENABLED)
146 DALI_LOG_TRACE_METHOD(gLogFilter);
148 DALI_LOG_INFO(gLogFilter, Debug::General, " Pan Event\n");
149 DALI_LOG_INFO(gLogFilter, Debug::General, " State: %s Touches: %d Time: %d TimeDelta: %d\n", GESTURE_STATES[static_cast<uint8_t>(panEvent.state)], panEvent.numberOfTouches, panEvent.time, panEvent.timeDelta);
150 DALI_LOG_INFO(gLogFilter, Debug::General, " Positions: Current: (%.0f, %.0f), Previous: (%.0f, %.0f)\n", panEvent.currentPosition.x, panEvent.currentPosition.y, panEvent.previousPosition.x, panEvent.previousPosition.y);
153 switch(panEvent.state)
155 case GestureState::POSSIBLE:
157 mCurrentPanEmitters.clear();
160 HitTestAlgorithm::Results hitTestResults;
161 if(HitTest(scene, panEvent.currentPosition, hitTestResults))
163 SetActor(&GetImplementation(hitTestResults.actor));
164 mPossiblePanPosition = panEvent.currentPosition;
169 case GestureState::STARTED:
171 // Requires a core update
174 // The pan gesture should only be sent to the gesture detector which first received it so that
175 // it can be told when the gesture ends as well.
177 HitTestAlgorithm::Results hitTestResults;
178 HitTest(scene, panEvent.previousPosition, hitTestResults); // Hit Test previous position
180 if(hitTestResults.actor)
182 // If the current hit actor is different from the one we touched down on then set accordingly & update initial pan position
183 if(&GetImplementation(hitTestResults.actor) != GetCurrentGesturedActor())
185 mPossiblePanPosition = panEvent.previousPosition;
186 SetActor(&GetImplementation(hitTestResults.actor));
189 // Record the current render-task for Screen->Actor coordinate conversions
190 mCurrentRenderTask = hitTestResults.renderTask;
192 // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
193 mCurrentPanEvent = &panEvent;
194 ProcessAndEmit(hitTestResults);
195 mCurrentPanEvent = nullptr;
200 mCurrentPanEmitters.clear();
205 case GestureState::CONTINUING:
207 // Requires a core update
213 case GestureState::FINISHED:
214 case GestureState::CANCELLED:
216 // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
217 // Check if actor is still touchable.
219 Actor* currentGesturedActor = GetCurrentGesturedActor();
220 if(currentGesturedActor)
222 if(currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask)
224 GestureDetectorContainer outsideTouchesRangeEmitters;
226 // Removes emitters that no longer have the actor attached
227 // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
228 GestureDetectorContainer::iterator endIter = std::remove_if(mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters));
229 mCurrentPanEmitters.erase(endIter, mCurrentPanEmitters.end());
233 if(!outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty())
235 currentGesturedActor->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y);
237 // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
238 EmitPanSignal(currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, GestureState::FINISHED, mCurrentRenderTask);
239 EmitPanSignal(currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
242 if(mCurrentPanEmitters.empty())
244 // If we have no emitters attached then clear pan actor as well.
248 // Clear current gesture detectors if pan gesture has ended or been cancelled.
249 if((panEvent.state == GestureState::FINISHED) || (panEvent.state == GestureState::CANCELLED))
251 mCurrentPanEmitters.clear();
257 mCurrentPanEmitters.clear();
264 case GestureState::CLEAR:
266 DALI_ABORT("Incorrect state received from Integration layer: CLEAR\n");
272 void PanGestureProcessor::AddGestureDetector(PanGestureDetector* gestureDetector, Scene& scene, int32_t minDistance, int32_t minPanEvents)
274 bool firstRegistration(mPanGestureDetectors.empty());
276 mPanGestureDetectors.push_back(gestureDetector);
278 if(firstRegistration)
280 mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
281 mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
282 mMaxMotionEventAge = gestureDetector->GetMaximumMotionEventAge();
284 PanGestureRequest request;
285 request.minTouches = mMinTouchesRequired;
286 request.maxTouches = mMaxTouchesRequired;
287 request.maxMotionEventAge = mMaxMotionEventAge;
289 Size size = scene.GetSize();
290 mGestureRecognizer = new PanGestureRecognizer(*this, Vector2(size.width, size.height), static_cast<const PanGestureRequest&>(request), minDistance, minPanEvents);
298 void PanGestureProcessor::RemoveGestureDetector(PanGestureDetector* gestureDetector)
300 if(!mCurrentPanEmitters.empty())
302 // Check if the removed detector was one that is currently being panned and remove it from emitters.
303 GestureDetectorContainer::iterator endIter = std::remove(mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector);
304 mCurrentPanEmitters.erase(endIter, mCurrentPanEmitters.end());
306 // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
307 if(mCurrentPanEmitters.empty())
313 // Find the detector...
314 PanGestureDetectorContainer::iterator endIter = std::remove(mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector);
315 DALI_ASSERT_DEBUG(endIter != mPanGestureDetectors.end());
318 mPanGestureDetectors.erase(endIter, mPanGestureDetectors.end());
320 if(mPanGestureDetectors.empty())
322 mGestureRecognizer = nullptr;
330 void PanGestureProcessor::GestureDetectorUpdated(PanGestureDetector* gestureDetector)
332 DALI_ASSERT_DEBUG(find(mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector) != mPanGestureDetectors.end());
337 bool PanGestureProcessor::SetPanGestureProperties(const Dali::PanGesture& pan)
339 // If we are currently processing a pan gesture then just ignore
340 if(mCurrentPanEmitters.empty() && mSceneObject)
342 const PanGesture& panImpl(GetImplementation(pan));
344 // We update the scene object directly rather than sending a message.
345 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
346 mSceneObject->AddGesture(panImpl);
348 if(GestureState::STARTED == panImpl.GetState() || GestureState::CONTINUING == panImpl.GetState())
357 void PanGestureProcessor::EnableProfiling()
359 mSceneObject->EnableProfiling();
362 void PanGestureProcessor::SetPredictionMode(int mode)
364 if((mode < 0) || (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)
394 if((mode < 0) || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES))
396 mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
398 SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
399 mSceneObject->SetSmoothingMode(modeEnum);
402 void PanGestureProcessor::SetSmoothingAmount(float amount)
404 mSceneObject->SetSmoothingAmount(amount);
407 void PanGestureProcessor::SetUseActualTimes(bool value)
409 mSceneObject->SetUseActualTimes(value);
412 void PanGestureProcessor::SetInterpolationTimeRange(int value)
414 mSceneObject->SetInterpolationTimeRange(value);
417 void PanGestureProcessor::SetScalarOnlyPredictionEnabled(bool value)
419 mSceneObject->SetScalarOnlyPredictionEnabled(value);
422 void PanGestureProcessor::SetTwoPointPredictionEnabled(bool value)
424 mSceneObject->SetTwoPointPredictionEnabled(value);
427 void PanGestureProcessor::SetTwoPointInterpolatePastTime(int value)
429 mSceneObject->SetTwoPointInterpolatePastTime(value);
432 void PanGestureProcessor::SetTwoPointVelocityBias(float value)
434 mSceneObject->SetTwoPointVelocityBias(value);
437 void PanGestureProcessor::SetTwoPointAccelerationBias(float value)
439 mSceneObject->SetTwoPointAccelerationBias(value);
442 void PanGestureProcessor::SetMultitapSmoothingRange(int value)
444 mSceneObject->SetMultitapSmoothingRange(value);
447 const SceneGraph::PanGesture& PanGestureProcessor::GetSceneObject() const
449 return *mSceneObject;
452 void PanGestureProcessor::UpdateDetection()
454 DALI_ASSERT_DEBUG(!mPanGestureDetectors.empty());
456 uint32_t minimumRequired = std::numeric_limits<uint32_t>::max();
457 uint32_t maximumRequired = 0;
458 uint32_t maximumMotionEventAge = std::numeric_limits<uint32_t>::max();
460 for(PanGestureDetectorContainer::iterator iter = mPanGestureDetectors.begin(), endIter = mPanGestureDetectors.end(); iter != endIter; ++iter)
462 PanGestureDetector* detector(*iter);
466 uint32_t minimum = detector->GetMinimumTouchesRequired();
467 if(minimum < minimumRequired)
469 minimumRequired = minimum;
472 uint32_t maximum = detector->GetMaximumTouchesRequired();
473 if(maximum > maximumRequired)
475 maximumRequired = maximum;
478 uint32_t maximumAge = detector->GetMaximumMotionEventAge();
479 if(maximumAge > maximumMotionEventAge)
481 maximumMotionEventAge = maximumAge;
486 if((minimumRequired != mMinTouchesRequired) || (maximumRequired != mMaxTouchesRequired) || (maximumMotionEventAge != mMaxMotionEventAge))
488 mMinTouchesRequired = minimumRequired;
489 mMaxTouchesRequired = maximumRequired;
490 mMaxMotionEventAge = maximumMotionEventAge;
492 PanGestureRequest request;
493 request.minTouches = mMinTouchesRequired;
494 request.maxTouches = mMaxTouchesRequired;
495 request.maxMotionEventAge = mMaxMotionEventAge;
496 mGestureRecognizer->Update(request);
500 void PanGestureProcessor::EmitPanSignal(Actor* actor,
501 const GestureDetectorContainer& gestureDetectors,
502 const PanGestureEvent& panEvent,
503 Vector2 localCurrent,
505 RenderTaskPtr renderTask)
507 if(actor && !gestureDetectors.empty())
509 Internal::PanGesturePtr pan(new Internal::PanGesture(state));
511 pan->SetTime(panEvent.time);
513 pan->SetNumberOfTouches(panEvent.numberOfTouches);
514 pan->SetScreenPosition(panEvent.currentPosition);
515 pan->SetPosition(localCurrent);
517 RenderTask& renderTaskImpl(*renderTask.Get());
519 Vector2 localPrevious;
520 actor->ScreenToLocal(renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y);
522 pan->SetDisplacement(localCurrent - localPrevious);
523 Vector2 previousPos(panEvent.previousPosition);
524 if(state == GestureState::STARTED)
526 previousPos = mPossiblePanPosition;
529 pan->SetScreenDisplacement(panEvent.currentPosition - previousPos);
531 // Avoid dividing by 0
532 if(panEvent.timeDelta > 0)
535 velocity.x = pan->GetDisplacement().x / static_cast<float>(panEvent.timeDelta);
536 velocity.y = pan->GetDisplacement().y / static_cast<float>(panEvent.timeDelta);
537 pan->SetVelocity(velocity);
539 Vector2 screenVelocity;
540 screenVelocity.x = pan->GetScreenDisplacement().x / static_cast<float>(panEvent.timeDelta);
541 screenVelocity.y = pan->GetScreenDisplacement().y / static_cast<float>(panEvent.timeDelta);
542 pan->SetScreenVelocity(screenVelocity);
545 // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
546 // so we should use the last recorded velocity instead in this scenario.
547 if((state == GestureState::FINISHED) && (pan->GetScreenVelocity() == Vector2::ZERO) &&
548 (panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY))
550 pan->SetVelocity(mLastVelocity);
551 pan->SetScreenVelocity(mLastScreenVelocity);
555 // Store the current velocity for future iterations.
556 mLastVelocity = pan->GetVelocity();
557 mLastScreenVelocity = pan->GetScreenVelocity();
562 // We update the scene object directly rather than sending a message.
563 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
564 mSceneObject->AddGesture(*pan.Get());
567 Dali::Actor actorHandle(actor);
569 const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
570 for(GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter)
572 static_cast<PanGestureDetector*>(*iter)->EmitPanGestureSignal(actorHandle, Dali::PanGesture(pan.Get()));
577 void PanGestureProcessor::OnGesturedActorStageDisconnection()
579 mCurrentPanEmitters.clear();
582 bool PanGestureProcessor::CheckGestureDetector(GestureDetector* detector, Actor* actor)
584 DALI_ASSERT_DEBUG(mCurrentPanEvent);
587 PanGestureDetector* panDetector(static_cast<PanGestureDetector*>(detector));
589 if((mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired()) &&
590 (mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired()))
592 // Check if the detector requires directional panning.
593 if(panDetector->RequiresDirectionalPan() && mCurrentRenderTask)
595 // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
596 // the detector's criteria.
597 RenderTask& renderTaskImpl = *mCurrentRenderTask.Get();
599 Vector2 startPosition, currentPosition;
600 actor->ScreenToLocal(renderTaskImpl, startPosition.x, startPosition.y, mPossiblePanPosition.x, mPossiblePanPosition.y);
601 actor->ScreenToLocal(renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y);
602 Vector2 displacement(currentPosition - startPosition);
604 Radian angle(atanf(displacement.y / displacement.x));
606 /////////////////////////////
609 // Q3 (-,-) | Q4 (+,-) //
611 // ----------------- +x //
613 // Q2 (-,+) | Q1 (+,+) //
617 /////////////////////////////
619 // Quadrant 2: 180 degrees + angle
620 // Quadrant 3: angle - 180 degrees
622 /////////////////////////////
624 if(displacement.x < 0.0f)
626 if(displacement.y >= 0.0f)
629 angle.radian += Math::PI;
634 angle.radian -= Math::PI;
638 if(panDetector->CheckAngleAllowed(angle))
645 // Directional panning not required so we can use this actor and gesture detector.
652 void PanGestureProcessor::EmitGestureSignal(Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates)
654 DALI_ASSERT_DEBUG(mCurrentPanEvent);
656 mCurrentPanEmitters.clear();
659 actor->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y);
661 EmitPanSignal(actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask);
665 mCurrentPanEmitters = gestureDetectors;
670 } // namespace Internal