License conversion from Flora to Apache 2.0
[platform/core/uifw/dali-core.git] / dali / internal / event / events / touch-event-processor.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/event/events/touch-event-processor.h>
20
21 #if defined(DEBUG_ENABLED)
22 #include <sstream>
23 #endif
24
25 // INTERNAL INCLUDES
26 #include <dali/public-api/actors/renderable-actor.h>
27 #include <dali/public-api/math/vector2.h>
28 #include <dali/integration-api/debug.h>
29 #include <dali/integration-api/events/touch-event-integ.h>
30 #include <dali/internal/event/actors/actor-impl.h>
31 #include <dali/internal/event/actors/layer-impl.h>
32 #include <dali/internal/event/common/stage-impl.h>
33 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
34 #include <dali/internal/event/render-tasks/render-task-impl.h>
35
36 namespace Dali
37 {
38
39 namespace Internal
40 {
41
42 namespace
43 {
44
45 bool IsActuallySensitive( Actor* actor );
46
47 #if defined(DEBUG_ENABLED)
48 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TOUCH_PROCESSOR" );
49
50 const char * TOUCH_POINT_STATE[TouchPoint::Last] =
51 {
52   "Down",
53   "Up",
54   "Motion",
55   "Leave",
56   "Stationary",
57   "Interrupted",
58 };
59
60 static const Debug::LogLevel HIERARCHY_DEBUG_LOG_LEVEL( Debug::Verbose );
61
62 static bool HIERARCHY_GEOMETRY( false );
63 static bool HIERARCHY_SENSITIVITY( false );
64 static bool HIERARCHY_TOUCH_REQUIRED( false );
65 static bool HIERARCHY_HITTABLE( false );
66
67 /**
68  * Prints out all the children of the given actor when debug is enabled.
69  *
70  * @param[in]  actor  The actor whose children to print.
71  * @param[in]  level  The number of " | " to put in front of the children.
72  */
73 void PrintChildren( Dali::Actor actor, int level )
74 {
75   std::ostringstream output;
76
77   for ( int t = 0; t < level; ++t )
78   {
79     output << " | ";
80   }
81
82   output << actor.GetName() << "(" << actor.GetTypeName() << ", " << actor.GetObjectPtr() << ")";
83
84   if ( HIERARCHY_GEOMETRY )
85   {
86     output << " Pos: " << actor.GetCurrentWorldPosition() << " Size: " << actor.GetCurrentSize() << " Scale: " << actor.GetCurrentWorldScale();
87   }
88
89   if ( HIERARCHY_SENSITIVITY )
90   {
91     output << " Sensitivity: " << ( IsActuallySensitive( &GetImplementation( actor ) ) ? "True " : "False " );
92   }
93
94   if ( HIERARCHY_TOUCH_REQUIRED )
95   {
96     output << " TouchRequired: " << ( GetImplementation(actor).GetTouchRequired() ? "True " : "False " );
97   }
98
99   if ( HIERARCHY_HITTABLE )
100   {
101     output << " Hittable: " << ( GetImplementation(actor).IsHittable() ? "True " : "False " );
102   }
103
104   output << std::endl;
105
106   DALI_LOG_INFO( gLogFilter, HIERARCHY_DEBUG_LOG_LEVEL, output.str().c_str() );
107
108   ++level;
109   unsigned int numChildren=actor.GetChildCount();
110   for ( unsigned int i=0; i<numChildren; ++i )
111   {
112     PrintChildren( actor.GetChildAt(i), level );
113   }
114   --level;
115 }
116
117 /**
118  * Prints the entire hierarchy of the scene.
119  */
120 void PrintHierarchy()
121 {
122   if ( gLogFilter->IsEnabledFor( HIERARCHY_DEBUG_LOG_LEVEL ) )
123   {
124     PrintChildren( Dali::Stage().GetCurrent().GetRootLayer(), 0 );
125   }
126 }
127
128 #define PRINT_HIERARCHY PrintHierarchy()
129
130 #else // defined(DEBUG_ENABLED)
131
132 #define PRINT_HIERARCHY
133
134 #endif // defined(DEBUG_ENABLED)
135
136 /**
137  *  Recursively deliver events to the actor and its parents, until the event is consumed or the stage is reached.
138  */
139 Dali::Actor EmitTouchSignals( Dali::Actor actor, RenderTask& renderTask, const TouchEvent& event )
140 {
141   Dali::Actor consumedActor;
142
143   if ( actor )
144   {
145     Dali::Actor oldParent( actor.GetParent() );
146
147     Actor& actorImpl( GetImplementation(actor) );
148
149     bool consumed( false );
150
151     // Only emit the signal if the actor's touch signal has connections (or derived actor implementation requires touch).
152     if ( actorImpl.GetTouchRequired() )
153     {
154       consumed = actorImpl.EmitTouchEventSignal( event );
155     }
156
157     if ( consumed )
158     {
159       // One of this actor's listeners has consumed the event so set this actor as the consumed actor.
160       consumedActor = Dali::Actor( &actorImpl );
161     }
162     else
163     {
164       // The actor may have been removed/reparented during the signal callbacks.
165       Dali::Actor parent = actor.GetParent();
166
167       if ( parent &&
168            (parent == oldParent) )
169       {
170         // One of the actor's parents may consumed the event and they should be set as the consumed actor.
171         consumedActor = EmitTouchSignals( parent, renderTask, event );
172       }
173     }
174   }
175
176   return consumedActor;
177 }
178
179 /**
180  * Changes the state of the primary point to leave and emits the touch signals
181  */
182 Dali::Actor EmitTouchSignals( Actor* actor, RenderTask& renderTask, const TouchEvent& originalEvent, TouchPoint::State state )
183 {
184   TouchEvent touchEvent( originalEvent );
185   TouchPoint& primaryPoint = touchEvent.points[0];
186
187   actor->ScreenToLocal( renderTask, primaryPoint.local.x, primaryPoint.local.y, primaryPoint.screen.x, primaryPoint.screen.y );
188
189   primaryPoint.hitActor = actor;
190   primaryPoint.state = state;
191
192   return EmitTouchSignals( Dali::Actor(actor), renderTask, touchEvent );
193 }
194
195 /**
196  * In the hit test algorithm above we do not descend actor tree if it is insensitive, so here, we
197  * should also check if any of the actor's parents has become insensitive since we last processed
198  * it.
199  */
200 bool IsActuallySensitive( Actor* actor )
201 {
202   bool sensitive = true;
203
204   while ( actor && sensitive )
205   {
206     sensitive = actor->IsSensitive();
207     actor = actor->GetParent();
208   }
209
210   return sensitive;
211 }
212
213 } // unnamed namespace
214
215 TouchEventProcessor::TouchEventProcessor( Stage& stage )
216 : mStage( stage ),
217   mLastPrimaryHitActor(),
218   mLastConsumedActor(),
219   mLastRenderTask()
220 {
221   DALI_LOG_TRACE_METHOD( gLogFilter );
222 }
223
224 TouchEventProcessor::~TouchEventProcessor()
225 {
226   DALI_LOG_TRACE_METHOD( gLogFilter );
227 }
228
229 void TouchEventProcessor::ProcessTouchEvent( const Integration::TouchEvent& event )
230 {
231   DALI_LOG_TRACE_METHOD( gLogFilter );
232
233   DALI_ASSERT_ALWAYS( !event.points.empty() && "Empty TouchEvent sent from Integration\n" );
234
235   Stage& stage = mStage;
236
237   PRINT_HIERARCHY;
238
239   // Copy so we can add the results of a hit-test.
240   TouchEvent touchEvent( event.time );
241
242   // 1) Check if it is an interrupted event - we should inform our last primary hit actor about this
243   //    and emit the stage signal as well.
244
245   if ( event.points[0].state == TouchPoint::Interrupted )
246   {
247     Dali::Actor consumingActor;
248     touchEvent.points.push_back(event.points[0]);
249
250     if ( mLastRenderTask )
251     {
252       RenderTask& lastRenderTaskImpl( GetImplementation( mLastRenderTask ) );
253
254       Actor* lastPrimaryHitActor( mLastPrimaryHitActor.GetActor() );
255       if ( lastPrimaryHitActor )
256       {
257         Dali::Actor lastPrimaryHitActorHandle( lastPrimaryHitActor );
258         touchEvent.points[0].hitActor = lastPrimaryHitActorHandle;
259         consumingActor = EmitTouchSignals( lastPrimaryHitActorHandle, lastRenderTaskImpl, touchEvent );
260       }
261
262       // If the last consumed actor was different to the primary hit actor then inform it as well (if it has not already been informed).
263       Actor* lastConsumedActor( mLastConsumedActor.GetActor() );
264       if ( lastConsumedActor &&
265            lastConsumedActor != lastPrimaryHitActor &&
266            lastConsumedActor != consumingActor )
267       {
268         Dali::Actor lastConsumedActorHandle( lastConsumedActor );
269         touchEvent.points[0].hitActor = lastConsumedActorHandle;
270         EmitTouchSignals( lastConsumedActorHandle, lastRenderTaskImpl, touchEvent );
271       }
272     }
273
274     mLastPrimaryHitActor.SetActor( NULL );
275     mLastConsumedActor.SetActor( NULL );
276     mLastRenderTask.Reset();
277
278     touchEvent.points[0].hitActor = NULL;
279     mStage.EmitTouchedSignal( touchEvent );
280
281     return; // No need for hit testing
282   }
283
284   // 2) Hit Testing.
285
286   DALI_LOG_INFO( gLogFilter, Debug::Concise, "\n" );
287   DALI_LOG_INFO( gLogFilter, Debug::General, "Point(s): %d\n", event.GetPointCount() );
288
289   Dali::RenderTask currentRenderTask;
290
291   for ( TouchPointContainerConstIterator iter = event.points.begin(), beginIter = event.points.begin(), endIter = event.points.end(); iter != endIter; ++iter )
292   {
293     HitTestAlgorithm::Results hitTestResults;
294     HitTestAlgorithm::HitTest( stage, iter->screen, hitTestResults );
295
296     TouchPoint newPoint( iter->deviceId, iter->state, iter->screen.x, iter->screen.y );
297     newPoint.hitActor = hitTestResults.actor;
298     newPoint.local = hitTestResults.actorCoordinates;
299
300     touchEvent.points.push_back( newPoint );
301
302     DALI_LOG_INFO( gLogFilter, Debug::General, "  State(%s), Screen(%.0f, %.0f), HitActor(%p, %s), Local(%.2f, %.2f)\n",
303                    TOUCH_POINT_STATE[iter->state], iter->screen.x, iter->screen.y,
304                    ( hitTestResults.actor ? (void*)&hitTestResults.actor.GetBaseObject() : NULL ),
305                    ( hitTestResults.actor ? hitTestResults.actor.GetName().c_str() : "" ),
306                    hitTestResults.actorCoordinates.x, hitTestResults.actorCoordinates.y );
307
308     // Only set the currentRenderTask for the primary hit actor.
309     if ( iter == beginIter && hitTestResults.renderTask )
310     {
311       currentRenderTask = hitTestResults.renderTask;
312     }
313   }
314
315   // 3) Recursively deliver events to the actor and its parents, until the event is consumed or the stage is reached.
316
317   // Emit the touch signal
318   Dali::Actor consumedActor;
319   if ( currentRenderTask )
320   {
321     consumedActor = EmitTouchSignals( touchEvent.points[0].hitActor, GetImplementation( currentRenderTask ), touchEvent );
322   }
323
324   TouchPoint& primaryPoint = touchEvent.points[0];
325   Dali::Actor primaryHitActor = primaryPoint.hitActor;
326   TouchPoint::State primaryPointState = primaryPoint.state;
327
328   DALI_LOG_INFO( gLogFilter, Debug::Concise, "PrimaryHitActor:     (%p) %s\n", primaryPoint.hitActor ? (void*)&primaryPoint.hitActor.GetBaseObject() : NULL, primaryPoint.hitActor ? primaryPoint.hitActor.GetName().c_str() : "" );
329   DALI_LOG_INFO( gLogFilter, Debug::Concise, "ConsumedActor:       (%p) %s\n", consumedActor ? (void*)&consumedActor.GetBaseObject() : NULL, consumedActor ? consumedActor.GetName().c_str() : "" );
330
331   // 4) Check if the last primary hit actor requires a leave event and if it was different to the current primary
332   //    hit actor.  Also process the last consumed actor in the same manner.
333
334   if( (primaryPointState == TouchPoint::Motion) || (primaryPointState == TouchPoint::Up) || (primaryPointState == TouchPoint::Stationary) )
335   {
336     if ( mLastRenderTask )
337     {
338       Dali::Actor leaveEventConsumer;
339       RenderTask& lastRenderTaskImpl( GetImplementation( mLastRenderTask ) );
340
341       Actor* lastPrimaryHitActor( mLastPrimaryHitActor.GetActor() );
342       if( lastPrimaryHitActor &&
343           lastPrimaryHitActor != primaryHitActor &&
344           lastPrimaryHitActor != consumedActor )
345       {
346         if( lastPrimaryHitActor->IsHittable() && IsActuallySensitive( lastPrimaryHitActor ) )
347         {
348           if ( lastPrimaryHitActor->GetLeaveRequired() )
349           {
350             DALI_LOG_INFO( gLogFilter, Debug::Concise, "LeaveActor(Hit):     (%p) %s\n", (void*)lastPrimaryHitActor, lastPrimaryHitActor->GetName().c_str() );
351             leaveEventConsumer = EmitTouchSignals( mLastPrimaryHitActor.GetActor(), lastRenderTaskImpl, touchEvent, TouchPoint::Leave );
352           }
353         }
354         else
355         {
356           // At this point mLastPrimaryHitActor was touchable and sensitive in the previous touch event process but is not in the current one.
357           // An interrupted event is send to allow some actors to go back to their original state (i.e. Button controls)
358           DALI_LOG_INFO( gLogFilter, Debug::Concise, "InterruptedActor(Hit):     (%p) %s\n", (void*)lastPrimaryHitActor, lastPrimaryHitActor->GetName().c_str() );
359           leaveEventConsumer = EmitTouchSignals( mLastPrimaryHitActor.GetActor(), lastRenderTaskImpl, touchEvent, TouchPoint::Interrupted );
360         }
361       }
362
363       // Check if the motion event has been consumed by another actor's listener.  In this case, the previously
364       // consumed actor's listeners may need to be informed (through a leave event).
365       // Further checks here to ensure we do not signal the same actor twice for the same event.
366       Actor* lastConsumedActor( mLastConsumedActor.GetActor() );
367       if ( lastConsumedActor &&
368            lastConsumedActor != consumedActor &&
369            lastConsumedActor != lastPrimaryHitActor &&
370            lastConsumedActor != primaryHitActor &&
371            lastConsumedActor != leaveEventConsumer )
372       {
373         if( lastConsumedActor->IsHittable() && IsActuallySensitive( lastConsumedActor ) )
374         {
375           if( lastConsumedActor->GetLeaveRequired() )
376           {
377             DALI_LOG_INFO( gLogFilter, Debug::Concise, "LeaveActor(Consume): (%p) %s\n", (void*)lastConsumedActor, lastConsumedActor->GetName().c_str() );
378             EmitTouchSignals( lastConsumedActor, lastRenderTaskImpl, touchEvent, TouchPoint::Leave );
379           }
380         }
381         else
382         {
383           // At this point mLastConsumedActor was touchable and sensitive in the previous touch event process but is not in the current one.
384           // An interrupted event is send to allow some actors to go back to their original state (i.e. Button controls)
385           DALI_LOG_INFO( gLogFilter, Debug::Concise, "InterruptedActor(Consume):     (%p) %s\n", (void*)lastConsumedActor, lastConsumedActor->GetName().c_str() );
386           EmitTouchSignals( mLastConsumedActor.GetActor(), lastRenderTaskImpl, touchEvent, TouchPoint::Interrupted );
387         }
388       }
389     }
390   }
391
392   // 5) If our primary point is an Up event, then the primary point (in multi-touch) will change next
393   //    time so set our last primary actor to NULL.  Do the same to the last consumed actor as well.
394
395   if ( primaryPointState == TouchPoint::Up )
396   {
397     mLastPrimaryHitActor.SetActor( NULL );
398     mLastConsumedActor.SetActor( NULL );
399     mLastRenderTask.Reset();
400   }
401   else
402   {
403     // The primaryHitActor may have been removed from the stage so ensure it is still on the stage before setting members.
404     if ( primaryHitActor && primaryHitActor.OnStage() )
405     {
406       mLastPrimaryHitActor.SetActor( &GetImplementation( primaryHitActor ) );
407
408       // Only observe the consumed actor if we have a primaryHitActor (check if it is still on stage).
409       if ( consumedActor && consumedActor.OnStage() )
410       {
411         mLastConsumedActor.SetActor( &GetImplementation( consumedActor ) );
412       }
413       else
414       {
415         mLastConsumedActor.SetActor( NULL );
416       }
417
418       mLastRenderTask = currentRenderTask;
419     }
420     else
421     {
422       mLastPrimaryHitActor.SetActor( NULL );
423       mLastConsumedActor.SetActor( NULL );
424       mLastRenderTask.Reset();
425     }
426   }
427
428   // 6) Emit the stage touched event if required.
429   if ( touchEvent.GetPointCount() == 1 ) // Only want the first touch and the last release
430   {
431     switch ( primaryPointState )
432     {
433       case TouchPoint::Down:
434       case TouchPoint::Up:
435       {
436         mStage.EmitTouchedSignal( touchEvent );
437         break;
438       }
439
440       case TouchPoint::Motion:
441       case TouchPoint::Leave:
442       case TouchPoint::Stationary:
443       case TouchPoint::Interrupted:
444       case TouchPoint::Last:
445       {
446         // Ignore
447         break;
448       }
449     }
450   }
451 }
452
453 TouchEventProcessor::ActorObserver::ActorObserver()
454 : mActor ( NULL ),
455   mActorDisconnected(false)
456 {
457   DALI_LOG_TRACE_METHOD( gLogFilter );
458 }
459
460 TouchEventProcessor::ActorObserver::~ActorObserver()
461 {
462   DALI_LOG_TRACE_METHOD( gLogFilter );
463   SetActor( NULL );
464 }
465
466 Actor* TouchEventProcessor::ActorObserver::GetActor()
467 {
468   return mActorDisconnected ? NULL : mActor;
469 }
470
471 void TouchEventProcessor::ActorObserver::SetActor( Actor* actor )
472 {
473   DALI_LOG_TRACE_METHOD( gLogFilter );
474
475   if ( mActor != actor )
476   {
477     ResetActor();
478
479     mActor = actor;
480
481     if ( mActor )
482     {
483       mActor->AddObserver( *this );
484       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Start Observing:            %p\n", mActor);
485     }
486   }
487 }
488
489 void TouchEventProcessor::ActorObserver::ResetActor()
490 {
491   if ( mActor )
492   {
493     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Stop Observing:             %p\n", mActor);
494     mActor->RemoveObserver( *this );
495     mActor = NULL;
496     mActorDisconnected = false;
497   }
498 }
499
500 void TouchEventProcessor::ActorObserver::SceneObjectRemoved( ProxyObject& proxy )
501 {
502   DALI_LOG_TRACE_METHOD( gLogFilter );
503
504   if ( mActor == &proxy )
505   {
506     // do not call proxy.RemoveObserver here, proxy is currently iterating through observers... you wouldnt want to upset proxy now would you?
507     mActorDisconnected = true;
508   }
509 }
510
511 void TouchEventProcessor::ActorObserver::ProxyDestroyed(ProxyObject& proxy)
512 {
513   DALI_LOG_TRACE_METHOD( gLogFilter );
514
515   if ( mActor == &proxy )
516   {
517     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Stop Observing:             %p\n", mActor);
518     mActor = NULL;
519   }
520 }
521
522 } // namespace Internal
523
524 } // namespace Dali