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 mMaxMotionEventAge(std::numeric_limits<uint32_t>::max()),
132 mCurrentPanEvent(nullptr),
133 mSceneObject(SceneGraph::PanGesture::New()) // Create scene object to store pan information.
135 // Pass ownership to scene-graph; scene object lives for the lifecycle of UpdateManager
136 updateManager.SetPanGestureProcessor(mSceneObject);
139 PanGestureProcessor::~PanGestureProcessor()
141 mSceneObject = nullptr; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
144 void PanGestureProcessor::Process(Scene& scene, const PanGestureEvent& panEvent)
146 #if defined(DEBUG_ENABLED)
147 DALI_LOG_TRACE_METHOD(gLogFilter);
149 DALI_LOG_INFO(gLogFilter, Debug::General, " Pan Event\n");
150 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);
151 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);
154 switch(panEvent.state)
156 case GestureState::POSSIBLE:
158 mCurrentPanEmitters.clear();
161 HitTestAlgorithm::Results hitTestResults;
162 if(HitTest(scene, panEvent.currentPosition, hitTestResults))
164 SetActor(&GetImplementation(hitTestResults.actor));
165 mPossiblePanPosition = panEvent.currentPosition;
170 case GestureState::STARTED:
172 // Requires a core update
175 // The pan gesture should only be sent to the gesture detector which first received it so that
176 // it can be told when the gesture ends as well.
178 HitTestAlgorithm::Results hitTestResults;
179 HitTest(scene, panEvent.previousPosition, hitTestResults); // Hit Test previous position
181 if(hitTestResults.actor)
183 // If the current hit actor is different from the one we touched down on then set accordingly & update initial pan position
184 if(&GetImplementation(hitTestResults.actor) != GetCurrentGesturedActor())
186 mPossiblePanPosition = panEvent.previousPosition;
187 SetActor(&GetImplementation(hitTestResults.actor));
190 // Record the current render-task for Screen->Actor coordinate conversions
191 mCurrentRenderTask = hitTestResults.renderTask;
193 // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
194 mCurrentPanEvent = &panEvent;
195 ProcessAndEmit(hitTestResults);
196 mCurrentPanEvent = nullptr;
201 mCurrentPanEmitters.clear();
206 case GestureState::CONTINUING:
208 // Requires a core update
214 case GestureState::FINISHED:
215 case GestureState::CANCELLED:
217 // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
218 // Check if actor is still touchable.
220 Actor* currentGesturedActor = GetCurrentGesturedActor();
221 if(currentGesturedActor)
223 if(currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask)
225 GestureDetectorContainer outsideTouchesRangeEmitters;
227 // Removes emitters that no longer have the actor attached
228 // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
229 GestureDetectorContainer::iterator endIter = std::remove_if(mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters));
230 mCurrentPanEmitters.erase(endIter, mCurrentPanEmitters.end());
234 if(!outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty())
236 currentGesturedActor->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y);
238 // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
239 EmitPanSignal(currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, GestureState::FINISHED, mCurrentRenderTask);
240 EmitPanSignal(currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
243 if(mCurrentPanEmitters.empty())
245 // If we have no emitters attached then clear pan actor as well.
249 // Clear current gesture detectors if pan gesture has ended or been cancelled.
250 if((panEvent.state == GestureState::FINISHED) || (panEvent.state == GestureState::CANCELLED))
252 mCurrentPanEmitters.clear();
258 mCurrentPanEmitters.clear();
265 case GestureState::CLEAR:
267 DALI_ABORT("Incorrect state received from Integration layer: CLEAR\n");
273 void PanGestureProcessor::AddGestureDetector(PanGestureDetector* gestureDetector, Scene& scene, int32_t minDistance, int32_t minPanEvents)
275 bool firstRegistration(mPanGestureDetectors.empty());
277 mPanGestureDetectors.push_back(gestureDetector);
279 if(firstRegistration)
281 mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
282 mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
283 mMaxMotionEventAge = gestureDetector->GetMaximumMotionEventAge();
285 PanGestureRequest request;
286 request.minTouches = mMinTouchesRequired;
287 request.maxTouches = mMaxTouchesRequired;
288 request.maxMotionEventAge = mMaxMotionEventAge;
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 = nullptr;
331 void PanGestureProcessor::GestureDetectorUpdated(PanGestureDetector* gestureDetector)
333 DALI_ASSERT_DEBUG(find(mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector) != mPanGestureDetectors.end());
338 bool PanGestureProcessor::SetPanGestureProperties(const Dali::PanGesture& pan)
340 // If we are currently processing a pan gesture then just ignore
341 if(mCurrentPanEmitters.empty() && mSceneObject)
343 const PanGesture& panImpl(GetImplementation(pan));
345 // We update the scene object directly rather than sending a message.
346 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
347 mSceneObject->AddGesture(panImpl);
349 if(GestureState::STARTED == panImpl.GetState() || GestureState::CONTINUING == panImpl.GetState())
358 void PanGestureProcessor::EnableProfiling()
360 mSceneObject->EnableProfiling();
363 void PanGestureProcessor::SetPredictionMode(int mode)
365 if((mode < 0) || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES))
367 mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
369 SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
370 mSceneObject->SetPredictionMode(modeEnum);
373 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
375 mSceneObject->SetPredictionAmount(amount);
378 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
380 mSceneObject->SetMaximumPredictionAmount(amount);
383 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
385 mSceneObject->SetMinimumPredictionAmount(amount);
388 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
390 mSceneObject->SetPredictionAmountAdjustment(amount);
393 void PanGestureProcessor::SetSmoothingMode(int mode)
395 if((mode < 0) || (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 uint32_t minimumRequired = std::numeric_limits<uint32_t>::max();
458 uint32_t maximumRequired = 0;
459 uint32_t maximumMotionEventAge = std::numeric_limits<uint32_t>::max();
461 for(PanGestureDetectorContainer::iterator iter = mPanGestureDetectors.begin(), endIter = mPanGestureDetectors.end(); iter != endIter; ++iter)
463 PanGestureDetector* detector(*iter);
467 uint32_t minimum = detector->GetMinimumTouchesRequired();
468 if(minimum < minimumRequired)
470 minimumRequired = minimum;
473 uint32_t maximum = detector->GetMaximumTouchesRequired();
474 if(maximum > maximumRequired)
476 maximumRequired = maximum;
479 uint32_t maximumAge = detector->GetMaximumMotionEventAge();
480 if(maximumAge < maximumMotionEventAge)
482 maximumMotionEventAge = maximumAge;
487 if((minimumRequired != mMinTouchesRequired) || (maximumRequired != mMaxTouchesRequired) || (maximumMotionEventAge != mMaxMotionEventAge))
489 mMinTouchesRequired = minimumRequired;
490 mMaxTouchesRequired = maximumRequired;
491 mMaxMotionEventAge = maximumMotionEventAge;
493 PanGestureRequest request;
494 request.minTouches = mMinTouchesRequired;
495 request.maxTouches = mMaxTouchesRequired;
496 request.maxMotionEventAge = mMaxMotionEventAge;
497 mGestureRecognizer->Update(request);
501 void PanGestureProcessor::EmitPanSignal(Actor* actor,
502 const GestureDetectorContainer& gestureDetectors,
503 const PanGestureEvent& panEvent,
504 Vector2 localCurrent,
506 RenderTaskPtr renderTask)
508 if(actor && !gestureDetectors.empty())
510 Internal::PanGesturePtr pan(new Internal::PanGesture(state));
512 pan->SetTime(panEvent.time);
514 pan->SetNumberOfTouches(panEvent.numberOfTouches);
515 pan->SetScreenPosition(panEvent.currentPosition);
516 pan->SetPosition(localCurrent);
518 RenderTask& renderTaskImpl(*renderTask.Get());
520 Vector2 localPrevious;
521 actor->ScreenToLocal(renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y);
523 pan->SetDisplacement(localCurrent - localPrevious);
524 Vector2 previousPos(panEvent.previousPosition);
525 if(state == GestureState::STARTED)
527 previousPos = mPossiblePanPosition;
530 pan->SetScreenDisplacement(panEvent.currentPosition - previousPos);
532 // Avoid dividing by 0
533 if(panEvent.timeDelta > 0)
536 velocity.x = pan->GetDisplacement().x / static_cast<float>(panEvent.timeDelta);
537 velocity.y = pan->GetDisplacement().y / static_cast<float>(panEvent.timeDelta);
538 pan->SetVelocity(velocity);
540 Vector2 screenVelocity;
541 screenVelocity.x = pan->GetScreenDisplacement().x / static_cast<float>(panEvent.timeDelta);
542 screenVelocity.y = pan->GetScreenDisplacement().y / static_cast<float>(panEvent.timeDelta);
543 pan->SetScreenVelocity(screenVelocity);
546 // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
547 // so we should use the last recorded velocity instead in this scenario.
548 if((state == GestureState::FINISHED) && (pan->GetScreenVelocity() == Vector2::ZERO) &&
549 (panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY))
551 pan->SetVelocity(mLastVelocity);
552 pan->SetScreenVelocity(mLastScreenVelocity);
556 // Store the current velocity for future iterations.
557 mLastVelocity = pan->GetVelocity();
558 mLastScreenVelocity = pan->GetScreenVelocity();
563 // We update the scene object directly rather than sending a message.
564 // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
565 mSceneObject->AddGesture(*pan.Get());
568 Dali::Actor actorHandle(actor);
570 const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
571 for(GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter)
573 static_cast<PanGestureDetector*>(*iter)->EmitPanGestureSignal(actorHandle, Dali::PanGesture(pan.Get()));
578 void PanGestureProcessor::OnGesturedActorStageDisconnection()
580 mCurrentPanEmitters.clear();
583 bool PanGestureProcessor::CheckGestureDetector(GestureDetector* detector, Actor* actor)
585 DALI_ASSERT_DEBUG(mCurrentPanEvent);
588 PanGestureDetector* panDetector(static_cast<PanGestureDetector*>(detector));
590 if((mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired()) &&
591 (mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired()))
593 // Check if the detector requires directional panning.
594 if(panDetector->RequiresDirectionalPan() && mCurrentRenderTask)
596 // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
597 // the detector's criteria.
598 RenderTask& renderTaskImpl = *mCurrentRenderTask.Get();
600 Vector2 startPosition, currentPosition;
601 actor->ScreenToLocal(renderTaskImpl, startPosition.x, startPosition.y, mPossiblePanPosition.x, mPossiblePanPosition.y);
602 actor->ScreenToLocal(renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y);
603 Vector2 displacement(currentPosition - startPosition);
605 Radian angle(atanf(displacement.y / displacement.x));
607 /////////////////////////////
610 // Q3 (-,-) | Q4 (+,-) //
612 // ----------------- +x //
614 // Q2 (-,+) | Q1 (+,+) //
618 /////////////////////////////
620 // Quadrant 2: 180 degrees + angle
621 // Quadrant 3: angle - 180 degrees
623 /////////////////////////////
625 if(displacement.x < 0.0f)
627 if(displacement.y >= 0.0f)
630 angle.radian += Math::PI;
635 angle.radian -= Math::PI;
639 if(panDetector->CheckAngleAllowed(angle))
646 // Directional panning not required so we can use this actor and gesture detector.
653 void PanGestureProcessor::EmitGestureSignal(Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates)
655 DALI_ASSERT_DEBUG(mCurrentPanEvent);
657 mCurrentPanEmitters.clear();
660 actor->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y);
662 EmitPanSignal(actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask);
666 mCurrentPanEmitters = gestureDetectors;
671 } // namespace Internal