[dali_1.0.39] Merge branch 'tizen'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / decorator / text-decorator.cpp
1 /*
2  * Copyright (c) 2015 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-toolkit/internal/text/decorator/text-decorator.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/actors/actor.h>
24 #include <dali/public-api/adaptor-framework/timer.h>
25 #include <dali/public-api/actors/image-actor.h>
26 #include <dali/public-api/actors/layer.h>
27 #include <dali/public-api/actors/mesh-actor.h>
28 #include <dali/public-api/animation/constraint.h>
29 #include <dali/public-api/common/constants.h>
30 #include <dali/public-api/common/stage.h>
31 #include <dali/public-api/events/tap-gesture.h>
32 #include <dali/public-api/events/tap-gesture-detector.h>
33 #include <dali/public-api/events/pan-gesture.h>
34 #include <dali/public-api/events/pan-gesture-detector.h>
35 #include <dali/public-api/geometry/mesh.h>
36 #include <dali/public-api/geometry/mesh-data.h>
37 #include <dali/public-api/images/resource-image.h>
38 #include <dali/public-api/math/rect.h>
39 #include <dali/public-api/math/vector2.h>
40 #include <dali/public-api/math/vector4.h>
41 #include <dali/public-api/object/property-notification.h>
42 #include <dali/public-api/signals/connection-tracker.h>
43
44 // INTERNAL INCLUDES
45 #include <dali-toolkit/public-api/controls/control.h>
46 #include <dali-toolkit/public-api/controls/control-impl.h>
47 #include <dali-toolkit/public-api/controls/buttons/push-button.h>
48 #include <dali-toolkit/public-api/controls/default-controls/solid-color-actor.h>
49 #include <dali-toolkit/public-api/controls/text-controls/text-label.h>
50 #include <dali-toolkit/public-api/controls/text-controls/text-selection-popup.h>
51
52 #ifdef DEBUG_ENABLED
53 #define DECORATOR_DEBUG
54
55 #endif
56
57 namespace Dali
58 {
59 namespace Internal
60 {
61 namespace
62 {
63 #ifdef DECORATOR_DEBUG
64 Integration::Log::Filter* gLogFilter( Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR") );
65 #endif
66 }
67 }
68 }
69
70
71 // Local Data
72 namespace
73 {
74
75 const char* DEFAULT_GRAB_HANDLE_IMAGE( DALI_IMAGE_DIR "insertpoint-icon.png" );
76 const char* DEFAULT_SELECTION_HANDLE_ONE( DALI_IMAGE_DIR "text-input-selection-handle-left.png" );
77 const char* DEFAULT_SELECTION_HANDLE_TWO( DALI_IMAGE_DIR "text-input-selection-handle-right.png" );
78 //const char* DEFAULT_SELECTION_HANDLE_ONE_PRESSED( DALI_IMAGE_DIR "text-input-selection-handle-left-press.png" );
79 //const char* DEFAULT_SELECTION_HANDLE_TWO_PRESSED( DALI_IMAGE_DIR "text-input-selection-handle-right-press.png" );
80
81 const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE( 1.5f, 2.0f, 1.0f );
82 const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE( 1.5f, 1.5f, 1.0f );
83
84 const unsigned int CURSOR_BLINK_INTERVAL = 500u; // Cursor blink interval
85 const float TO_MILLISECONDS = 1000.f;
86 const float TO_SECONDS = 1.f / 1000.f;
87
88 const float DISPLAYED_HIGHLIGHT_Z_OFFSET( -0.05f );
89
90 /**
91  * structure to hold coordinates of each quad, which will make up the mesh.
92  */
93 struct QuadCoordinates
94 {
95   /**
96    * Default constructor
97    */
98   QuadCoordinates()
99   {
100   }
101
102   /**
103    * Constructor
104    * @param[in] x1 left co-ordinate
105    * @param[in] y1 top co-ordinate
106    * @param[in] x2 right co-ordinate
107    * @param[in] y2 bottom co-ordinate
108    */
109   QuadCoordinates(float x1, float y1, float x2, float y2)
110   : min(x1, y1),
111     max(x2, y2)
112   {
113   }
114
115   Dali::Vector2 min;                          ///< top-left (minimum) position of quad
116   Dali::Vector2 max;                          ///< bottom-right (maximum) position of quad
117 };
118
119 typedef std::vector<QuadCoordinates> QuadContainer;
120
121 /**
122  * @brief Takes a bounding rectangle in the local coordinates of an actor and returns the world coordinates Bounding Box.
123  * @param[in] boundingRectangle local bounding
124  * @param[out] Vector4 World coordinate bounding Box.
125  */
126 void LocalToWorldCoordinatesBoundingBox( const Dali::Rect<int>& boundingRectangle, Dali::Vector4& boundingBox )
127 {
128   // Convert to world coordinates and store as a Vector4 to be compatible with Property Notifications.
129   Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
130
131   const float originX = boundingRectangle.x - 0.5f * stageSize.width;
132   const float originY = boundingRectangle.y - 0.5f * stageSize.height;
133
134   boundingBox = Dali::Vector4( originX,
135                                originY,
136                                originX + boundingRectangle.width,
137                                originY + boundingRectangle.height );
138 }
139
140
141 } // end of namespace
142
143 namespace Dali
144 {
145
146 namespace Toolkit
147 {
148
149 namespace Text
150 {
151
152 struct Decorator::Impl : public ConnectionTracker
153 {
154   struct CursorImpl
155   {
156     CursorImpl()
157     : color( Dali::Color::WHITE ),
158       position(),
159       cursorHeight( 0.0f ),
160       lineHeight( 0.0f )
161     {
162     }
163
164     Vector4 color;
165     Vector2 position;
166     float cursorHeight;
167     float lineHeight;
168   };
169
170   struct SelectionHandleImpl
171   {
172     SelectionHandleImpl()
173     : position(),
174       lineHeight( 0.0f ),
175       flipped( false )
176     {
177     }
178
179     ImageActor actor;
180     Actor grabArea;
181
182     Image pressedImage;
183     Image releasedImage;
184
185     Vector2 position;
186     float lineHeight; ///< Not the handle height
187     bool flipped;
188   };
189
190   Impl( Dali::Toolkit::Internal::Control& parent, Observer& observer )
191   : mTextControlParent( parent ),
192     mObserver( observer ),
193     mBoundingBox( Rect<int>() ),
194     mHighlightColor( 0.07f, 0.41f, 0.59f, 1.0f ), // light blue
195     mActiveCursor( ACTIVE_CURSOR_NONE ),
196     mCursorBlinkInterval( CURSOR_BLINK_INTERVAL ),
197     mCursorBlinkDuration( 0.0f ),
198     mGrabDisplacementX( 0.0f ),
199     mGrabDisplacementY( 0.0f ),
200     mActiveGrabHandle( false ),
201     mActiveSelection( false ),
202     mActiveCopyPastePopup( false ),
203     mCursorBlinkStatus( true )
204   {
205   }
206
207   /**
208    * Relayout of the decorations owned by the decorator.
209    * @param[in] size The Size of the UI control the decorator is adding it's decorations to.
210    */
211   void Relayout( const Vector2& size, const Vector2& scrollPosition )
212   {
213     // TODO - Remove this if nothing is active
214     CreateActiveLayer();
215
216     // Show or hide the cursors
217     CreateCursors();
218     if( mPrimaryCursor )
219     {
220       mPrimaryCursor.SetPosition( mCursor[PRIMARY_CURSOR].position.x + scrollPosition.x,
221                                   mCursor[PRIMARY_CURSOR].position.y + scrollPosition.y );
222       mPrimaryCursor.SetSize( Size( 1.0f, mCursor[PRIMARY_CURSOR].cursorHeight ) );
223     }
224     if( mSecondaryCursor )
225     {
226       mSecondaryCursor.SetPosition( mCursor[SECONDARY_CURSOR].position.x + scrollPosition.x,
227                                     mCursor[SECONDARY_CURSOR].position.y + scrollPosition.y );
228       mSecondaryCursor.SetSize( Size( 1.0f, mCursor[SECONDARY_CURSOR].cursorHeight ) );
229     }
230
231     // Show or hide the grab handle
232     if( mActiveGrabHandle )
233     {
234       SetupTouchEvents();
235
236       CreateGrabHandle();
237
238       mGrabHandle.SetPosition( mCursor[PRIMARY_CURSOR].position.x + scrollPosition.x,
239                                mCursor[PRIMARY_CURSOR].position.y + mCursor[PRIMARY_CURSOR].lineHeight + scrollPosition.y );
240     }
241     else if( mGrabHandle )
242     {
243       UnparentAndReset( mGrabHandle );
244     }
245
246     // Show or hide the selection handles/highlight
247     if( mActiveSelection )
248     {
249       SetupTouchEvents();
250
251       CreateSelectionHandles();
252
253       SelectionHandleImpl& primary = mSelectionHandle[ PRIMARY_SELECTION_HANDLE ];
254       primary.actor.SetPosition( primary.position.x + scrollPosition.x,
255                                  primary.position.y + primary.lineHeight + scrollPosition.y );
256
257       SelectionHandleImpl& secondary = mSelectionHandle[ SECONDARY_SELECTION_HANDLE ];
258       secondary.actor.SetPosition( secondary.position.x + scrollPosition.x,
259                                    secondary.position.y + secondary.lineHeight + scrollPosition.y );
260
261       CreateHighlight();
262       UpdateHighlight();
263     }
264     else
265     {
266       UnparentAndReset( mSelectionHandle[ PRIMARY_SELECTION_HANDLE ].actor );
267       UnparentAndReset( mSelectionHandle[ SECONDARY_SELECTION_HANDLE ].actor );
268       UnparentAndReset( mHighlightMeshActor );
269     }
270
271     if ( mActiveCopyPastePopup )
272     {
273       if ( !mCopyPastePopup )
274       {
275         mCopyPastePopup = TextSelectionPopup::New();
276 #ifdef DECORATOR_DEBUG
277         mCopyPastePopup.SetName("mCopyPastePopup");
278 #endif
279         mCopyPastePopup.SetAnchorPoint( AnchorPoint::CENTER );
280         mCopyPastePopup.OnRelayoutSignal().Connect( this,  &Decorator::Impl::PopUpRelayoutComplete  ); // Position popup after size negotiation
281         mActiveLayer.Add ( mCopyPastePopup );
282       }
283     }
284     else
285     {
286      if ( mCopyPastePopup )
287      {
288        UnparentAndReset( mCopyPastePopup );
289      }
290     }
291   }
292
293   void PopUpRelayoutComplete( Actor actor )
294   {
295     // Size negotiation for CopyPastePopup complete so can get the size and constrain position within bounding box.
296
297     mCopyPastePopup.OnRelayoutSignal().Disconnect( this, &Decorator::Impl::PopUpRelayoutComplete  );
298
299     Vector3 popupPosition( mCursor[PRIMARY_CURSOR].position.x, mCursor[PRIMARY_CURSOR].position.y -100.0f , 0.0f); //todo 100 to be an offset Property
300
301     Vector3 popupSize = Vector3( mCopyPastePopup.GetRelayoutSize( Dimension::WIDTH ), mCopyPastePopup.GetRelayoutSize( Dimension::HEIGHT ), 0.0f );
302
303     GetConstrainedPopupPosition( popupPosition, popupSize, AnchorPoint::CENTER, mActiveLayer, mBoundingBox );
304
305     SetUpPopUpPositionNotifications();
306
307     mCopyPastePopup.SetPosition( popupPosition ); //todo grabhandle(cursor) or selection handle positions to be used
308   }
309
310   void CreateCursor( ImageActor& cursor )
311   {
312     cursor = CreateSolidColorActor( Color::WHITE );
313     cursor.SetParentOrigin( ParentOrigin::TOP_LEFT ); // Need to set the default parent origin as CreateSolidColorActor() sets a different one.
314     cursor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
315   }
316
317   // Add or Remove cursor(s) from parent
318   void CreateCursors()
319   {
320     if( mActiveCursor == ACTIVE_CURSOR_NONE )
321     {
322       UnparentAndReset( mPrimaryCursor );
323       UnparentAndReset( mSecondaryCursor );
324     }
325     else
326     {
327       /* Create Primary and or Secondary Cursor(s) if active and add to parent */
328       if ( mActiveCursor == ACTIVE_CURSOR_PRIMARY ||
329            mActiveCursor == ACTIVE_CURSOR_BOTH )
330       {
331         if ( !mPrimaryCursor )
332         {
333           CreateCursor( mPrimaryCursor );
334 #ifdef DECORATOR_DEBUG
335           mPrimaryCursor.SetName( "PrimaryCursorActor" );
336 #endif
337           mActiveLayer.Add( mPrimaryCursor );
338         }
339       }
340
341       if ( mActiveCursor == ACTIVE_CURSOR_BOTH )
342       {
343         if ( !mSecondaryCursor )
344         {
345           CreateCursor( mSecondaryCursor );
346 #ifdef DECORATOR_DEBUG
347           mSecondaryCursor.SetName( "SecondaryCursorActor" );
348 #endif
349           mActiveLayer.Add( mSecondaryCursor );
350         }
351       }
352       else
353       {
354         UnparentAndReset( mSecondaryCursor );
355       }
356     }
357   }
358
359   bool OnCursorBlinkTimerTick()
360   {
361     // Cursor blinking
362     if ( mPrimaryCursor )
363     {
364       mPrimaryCursor.SetVisible( mCursorBlinkStatus );
365     }
366     if ( mSecondaryCursor )
367     {
368       mSecondaryCursor.SetVisible( mCursorBlinkStatus );
369     }
370
371     mCursorBlinkStatus = !mCursorBlinkStatus;
372
373     return true;
374   }
375
376   void SetupTouchEvents()
377   {
378     if ( !mTapDetector )
379     {
380       mTapDetector = TapGestureDetector::New();
381       mTapDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnTap );
382     }
383
384     if ( !mPanGestureDetector )
385     {
386       mPanGestureDetector = PanGestureDetector::New();
387       mPanGestureDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnPan );
388     }
389   }
390
391   void CreateActiveLayer()
392   {
393     if( !mActiveLayer )
394     {
395       Actor parent = mTextControlParent.Self();
396
397       mActiveLayer = Layer::New();
398 #ifdef DECORATOR_DEBUG
399       mActiveLayer.SetName ( "ActiveLayerActor" );
400 #endif
401
402       mActiveLayer.SetParentOrigin( ParentOrigin::CENTER );
403       mActiveLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
404       mActiveLayer.SetPositionInheritanceMode( USE_PARENT_POSITION );
405
406       parent.Add( mActiveLayer );
407     }
408
409     mActiveLayer.RaiseToTop();
410   }
411
412   void CreateGrabHandle()
413   {
414     if( !mGrabHandle )
415     {
416       if ( !mGrabHandleImage )
417       {
418         mGrabHandleImage = ResourceImage::New( DEFAULT_GRAB_HANDLE_IMAGE );
419       }
420
421       mGrabHandle = ImageActor::New( mGrabHandleImage );
422       mGrabHandle.SetAnchorPoint( AnchorPoint::TOP_CENTER );
423       mGrabHandle.SetDrawMode( DrawMode::OVERLAY );
424       // Area that Grab handle responds to, larger than actual handle so easier to move
425 #ifdef DECORATOR_DEBUG
426       mGrabHandle.SetName( "GrabHandleActor" );
427       if ( Dali::Internal::gLogFilter->IsEnabledFor( Debug::Verbose ) )
428       {
429         mGrabArea = Toolkit::CreateSolidColorActor( Vector4(0.0f, 0.0f, 0.0f, 0.0f), true, Color::RED, 1 );
430         mGrabArea.SetName( "GrabArea" );
431       }
432       else
433       {
434         mGrabArea = Actor::New();
435         mGrabArea.SetName( "GrabArea" );
436       }
437 #else
438       mGrabArea = Actor::New();
439 #endif
440
441       mGrabArea.SetParentOrigin( ParentOrigin::TOP_CENTER );
442       mGrabArea.SetAnchorPoint( AnchorPoint::TOP_CENTER );
443       mGrabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
444       mGrabArea.SetSizeModeFactor( DEFAULT_GRAB_HANDLE_RELATIVE_SIZE );
445       mGrabHandle.Add( mGrabArea );
446
447       mTapDetector.Attach( mGrabArea );
448       mPanGestureDetector.Attach( mGrabArea );
449
450       mActiveLayer.Add( mGrabHandle );
451     }
452   }
453
454   void CreateSelectionHandles()
455   {
456     SelectionHandleImpl& primary = mSelectionHandle[ PRIMARY_SELECTION_HANDLE ];
457     if ( !primary.actor )
458     {
459       if ( !primary.releasedImage )
460       {
461         primary.releasedImage = ResourceImage::New( DEFAULT_SELECTION_HANDLE_ONE );
462       }
463
464       primary.actor = ImageActor::New( primary.releasedImage );
465 #ifdef DECORATOR_DEBUG
466       primary.actor.SetName("SelectionHandleOne");
467 #endif
468       primary.actor.SetAnchorPoint( AnchorPoint::TOP_RIGHT ); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text.
469       primary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
470       primary.flipped = false;
471
472       primary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
473 #ifdef DECORATOR_DEBUG
474       primary.grabArea.SetName("SelectionHandleOneGrabArea");
475 #endif
476       primary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
477       primary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
478       primary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
479
480       mTapDetector.Attach( primary.grabArea );
481       mPanGestureDetector.Attach( primary.grabArea );
482       primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched );
483
484       primary.actor.Add( primary.grabArea );
485       mActiveLayer.Add( primary.actor );
486     }
487
488     SelectionHandleImpl& secondary = mSelectionHandle[ SECONDARY_SELECTION_HANDLE ];
489     if ( !secondary.actor )
490     {
491       if ( !secondary.releasedImage )
492       {
493         secondary.releasedImage = ResourceImage::New( DEFAULT_SELECTION_HANDLE_TWO );
494       }
495
496       secondary.actor = ImageActor::New( secondary.releasedImage );
497 #ifdef DECORATOR_DEBUG
498       secondary.actor.SetName("SelectionHandleTwo");
499 #endif
500       secondary.actor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
501       secondary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
502       secondary.flipped = false;
503
504       secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
505 #ifdef DECORATOR_DEBUG
506       secondary.grabArea.SetName("SelectionHandleTwoGrabArea");
507 #endif
508       secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
509       secondary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
510       secondary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
511
512       mTapDetector.Attach( secondary.grabArea );
513       mPanGestureDetector.Attach( secondary.grabArea );
514       secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched );
515
516       secondary.actor.Add( secondary.grabArea );
517       mActiveLayer.Add( secondary.actor );
518     }
519
520     //SetUpHandlePropertyNotifications(); TODO
521   }
522
523   void CreateHighlight()
524   {
525     if ( !mHighlightMeshActor )
526     {
527       mHighlightMaterial = Material::New( "HighlightMaterial" );
528       mHighlightMaterial.SetDiffuseColor( mHighlightColor );
529
530       mHighlightMeshData.SetMaterial( mHighlightMaterial );
531       mHighlightMeshData.SetHasNormals( true );
532
533       mHighlightMesh = Mesh::New( mHighlightMeshData );
534
535       mHighlightMeshActor = MeshActor::New( mHighlightMesh );
536 #ifdef DECORATOR_DEBUG
537       mHighlightMeshActor.SetName( "HighlightMeshActor" );
538 #endif
539       mHighlightMeshActor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
540       mHighlightMeshActor.SetPosition( 0.0f, 0.0f, DISPLAYED_HIGHLIGHT_Z_OFFSET );
541
542       Actor parent = mTextControlParent.Self();
543       parent.Add( mHighlightMeshActor );
544     }
545   }
546
547   void UpdateHighlight()
548   {
549     //  Construct a Mesh with a texture to be used as the highlight 'box' for selected text
550     //
551     //  Example scenarios where mesh is made from 3, 1, 2, 2 ,3 or 3 quads.
552     //
553     //   [ TOP   ]  [ TOP ]      [TOP ]  [ TOP    ]      [ TOP  ]      [ TOP  ]
554     //  [ MIDDLE ]             [BOTTOM]  [BOTTOM]      [ MIDDLE ]   [ MIDDLE  ]
555     //  [ BOTTOM]                                      [ MIDDLE ]   [ MIDDLE  ]
556     //                                                 [BOTTOM]     [ MIDDLE  ]
557     //                                                              [BOTTOM]
558     //
559     //  Each quad is created as 2 triangles.
560     //  Middle is just 1 quad regardless of its size.
561     //
562     //  (0,0)         (0,0)
563     //     0*    *2     0*       *2
564     //     TOP          TOP
565     //     3*    *1     3*       *1
566     //  4*       *1     4*     *6
567     //     MIDDLE         BOTTOM
568     //  6*       *5     7*     *5
569     //  6*    *8
570     //   BOTTOM
571     //  9*    *7
572     //
573
574     if ( mHighlightMesh && mHighlightMaterial && !mHighlightQuadList.empty() )
575     {
576       MeshData::VertexContainer vertices;
577       Dali::MeshData::FaceIndices faceIndices;
578
579       std::vector<QuadCoordinates>::iterator iter = mHighlightQuadList.begin();
580       std::vector<QuadCoordinates>::iterator endIter = mHighlightQuadList.end();
581
582       // vertex position defaults to (0 0 0)
583       MeshData::Vertex vertex;
584       // set normal for all vertices as (0 0 1) pointing outward from TextInput Actor.
585       vertex.nZ = 1.0f;
586
587       for(std::size_t v = 0; iter != endIter; ++iter,v+=4 )
588       {
589         // Add each quad geometry (a sub-selection) to the mesh data.
590
591         // 0-----1
592         // |\    |
593         // | \ A |
594         // |  \  |
595         // | B \ |
596         // |    \|
597         // 2-----3
598
599         QuadCoordinates& quad = *iter;
600         // top-left (v+0)
601         vertex.x = quad.min.x;
602         vertex.y = quad.min.y;
603         vertices.push_back( vertex );
604
605         // top-right (v+1)
606         vertex.x = quad.max.x;
607         vertex.y = quad.min.y;
608         vertices.push_back( vertex );
609
610         // bottom-left (v+2)
611         vertex.x = quad.min.x;
612         vertex.y = quad.max.y;
613         vertices.push_back( vertex );
614
615         // bottom-right (v+3)
616         vertex.x = quad.max.x;
617         vertex.y = quad.max.y;
618         vertices.push_back( vertex );
619
620         // triangle A (3, 1, 0)
621         faceIndices.push_back( v + 3 );
622         faceIndices.push_back( v + 1 );
623         faceIndices.push_back( v );
624
625         // triangle B (0, 2, 3)
626         faceIndices.push_back( v );
627         faceIndices.push_back( v + 2 );
628         faceIndices.push_back( v + 3 );
629
630         mHighlightMeshData.SetFaceIndices( faceIndices );
631       }
632
633       BoneContainer bones(0); // passed empty as bones not required
634       mHighlightMeshData.SetData( vertices, faceIndices, bones, mHighlightMaterial );
635       mHighlightMesh.UpdateMeshData( mHighlightMeshData );
636     }
637   }
638
639   void OnTap( Actor actor, const TapGesture& tap )
640   {
641     if( actor == mGrabHandle )
642     {
643       // TODO
644     }
645   }
646
647   void OnPan( Actor actor, const PanGesture& gesture )
648   {
649     if( actor == mGrabArea )
650     {
651       if( Gesture::Started == gesture.state )
652       {
653         mGrabDisplacementX = mGrabDisplacementY = 0;
654       }
655
656       mGrabDisplacementX += gesture.displacement.x;
657       mGrabDisplacementY += gesture.displacement.y;
658
659       const float x = mCursor[PRIMARY_CURSOR].position.x + mGrabDisplacementX;
660       const float y = mCursor[PRIMARY_CURSOR].position.y + mCursor[PRIMARY_CURSOR].lineHeight*0.5f + mGrabDisplacementY;
661
662       if( Gesture::Started    == gesture.state ||
663           Gesture::Continuing == gesture.state )
664       {
665         mObserver.GrabHandleEvent( GRAB_HANDLE_PRESSED, x, y );
666       }
667       else if( Gesture::Finished  == gesture.state ||
668                Gesture::Cancelled == gesture.state )
669       {
670         mObserver.GrabHandleEvent( GRAB_HANDLE_RELEASED, x, y );
671       }
672     }
673   }
674
675   bool OnHandleOneTouched( Actor actor, const TouchEvent& touch )
676   {
677     // TODO
678     return false;
679   }
680
681   bool OnHandleTwoTouched( Actor actor, const TouchEvent& touch )
682   {
683     // TODO
684     return false;
685   }
686
687   // Popup
688
689   float AlternatePopUpPositionRelativeToCursor()
690   {
691     float alternativePosition=0.0f;;
692
693     if ( mPrimaryCursor ) // Secondary cursor not used for paste
694     {
695       Cursor cursor = PRIMARY_CURSOR;
696       alternativePosition = mCursor[cursor].position.y;
697     }
698
699     const float popupHeight = 120.0f; // todo Set as a MaxSize Property in Control or retrieve from CopyPastePopup class.
700
701     if( mActiveGrabHandle )
702     {
703       // If grab handle enabled then position pop-up below the grab handle.
704       const Vector2 grabHandleSize( 59.0f, 56.0f ); // todo
705       const float BOTTOM_HANDLE_BOTTOM_OFFSET = 1.5; //todo Should be a property
706       alternativePosition +=  grabHandleSize.height  + popupHeight + BOTTOM_HANDLE_BOTTOM_OFFSET ;
707     }
708     else
709     {
710       alternativePosition += popupHeight;
711     }
712
713     return alternativePosition;
714   }
715
716   void PopUpLeavesVerticalBoundary( PropertyNotification& source )
717   {
718     float alternativeYPosition=0.0f;
719   // todo
720   //  if( mHighlightMeshActor ) // Text Selection mode
721   //  {
722   //    alternativePosition = AlternatePopUpPositionRelativeToSelectionHandles();
723   //  }
724   //  else // Not in Text Selection mode
725   //  {
726     // if can't be positioned above, then position below row.
727     alternativeYPosition = AlternatePopUpPositionRelativeToCursor();
728    // }
729     mCopyPastePopup.SetY( alternativeYPosition );
730   }
731
732
733   void SetUpPopUpPositionNotifications( )
734   {
735     // Note Property notifications ignore any set anchor point so conditions must allow for this.  Default is Top Left.
736
737     // Exceeding vertical boundary
738
739     Vector4 worldCoordinatesBoundingBox;
740     LocalToWorldCoordinatesBoundingBox( mBoundingBox, worldCoordinatesBoundingBox );
741
742     float popupHeight = mCopyPastePopup.GetRelayoutSize( Dimension::HEIGHT);
743
744     PropertyNotification verticalExceedNotification = mCopyPastePopup.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
745                                                       OutsideCondition( worldCoordinatesBoundingBox.y + popupHeight/2,
746                                                                         worldCoordinatesBoundingBox.w - popupHeight/2 ) );
747
748     verticalExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesVerticalBoundary );
749   }
750
751   void GetConstrainedPopupPosition( Vector3& requiredPopupPosition, Vector3& popupSize, Vector3 anchorPoint, Actor& parent, Rect<int>& boundingBox )
752   {
753     DALI_ASSERT_DEBUG ( "Popup parent not on stage" && parent.OnStage() )
754
755     // Parent must already by added to Stage for these Get calls to work
756     Vector3 parentAnchorPoint = parent.GetCurrentAnchorPoint();
757     Vector3 parentWorldPositionLeftAnchor = parent.GetCurrentWorldPosition() - parent.GetCurrentSize()*parentAnchorPoint;
758     Vector3 popupWorldPosition = parentWorldPositionLeftAnchor + requiredPopupPosition;  // Parent World position plus popup local position gives World Position
759     Vector3 popupDistanceFromAnchorPoint = popupSize*anchorPoint;
760
761     // Bounding rectangle is supplied as screen coordinates, bounding will be done in world coordinates.
762     Vector4 boundingRectangleWorld;
763     LocalToWorldCoordinatesBoundingBox( boundingBox, boundingRectangleWorld );
764
765     // Calculate distance to move popup (in local space) so fits within the boundary
766     float xOffSetToKeepWithinBounds = 0.0f;
767     if( popupWorldPosition.x - popupDistanceFromAnchorPoint.x < boundingRectangleWorld.x )
768     {
769       xOffSetToKeepWithinBounds = boundingRectangleWorld.x - ( popupWorldPosition.x - popupDistanceFromAnchorPoint.x );
770     }
771     else if ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x > boundingRectangleWorld.z )
772     {
773       xOffSetToKeepWithinBounds = boundingRectangleWorld.z - ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x );
774     }
775
776     // Ensure initial display of Popup is in alternative position if can not fit above. As Property notification will be a frame behind.
777     if ( popupWorldPosition.y - popupDistanceFromAnchorPoint.y < boundingRectangleWorld.y )
778     {
779       requiredPopupPosition.y = AlternatePopUpPositionRelativeToCursor();
780     }
781
782     requiredPopupPosition.x = requiredPopupPosition.x + xOffSetToKeepWithinBounds;
783   }
784
785   Internal::Control&  mTextControlParent;
786   Observer&           mObserver;
787
788   TapGestureDetector  mTapDetector;
789   PanGestureDetector  mPanGestureDetector;
790   Timer               mCursorBlinkTimer;          ///< Timer to signal cursor to blink
791
792   Layer               mActiveLayer;               ///< Layer for active handles and alike that ensures they are above all else.
793   ImageActor          mPrimaryCursor;
794   ImageActor          mSecondaryCursor;
795   ImageActor          mGrabHandle;
796   Actor               mGrabArea;
797   MeshActor           mHighlightMeshActor;        ///< Mesh Actor to display highlight
798   TextSelectionPopup  mCopyPastePopup;
799
800   Image               mCursorImage;
801   Image               mGrabHandleImage;
802   Mesh                mHighlightMesh;             ///< Mesh for highlight
803   MeshData            mHighlightMeshData;         ///< Mesh Data for highlight
804   Material            mHighlightMaterial;         ///< Material used for highlight
805
806   CursorImpl          mCursor[CURSOR_COUNT];
807   SelectionHandleImpl mSelectionHandle[SELECTION_HANDLE_COUNT];
808   QuadContainer       mHighlightQuadList;         ///< Sub-selections that combine to create the complete selection highlight
809
810   Rect<int>           mBoundingBox;
811   Vector4             mHighlightColor;            ///< Color of the highlight
812
813   unsigned int        mActiveCursor;
814   unsigned int        mCursorBlinkInterval;
815   float               mCursorBlinkDuration;
816   float               mGrabDisplacementX;
817   float               mGrabDisplacementY;
818
819   bool                mActiveGrabHandle:1;
820   bool                mActiveSelection:1;
821   bool                mActiveCopyPastePopup:1;
822   bool                mCursorBlinkStatus:1;       ///< Flag to switch between blink on and blink off
823 };
824
825 DecoratorPtr Decorator::New( Internal::Control& parent, Observer& observer )
826 {
827   return DecoratorPtr( new Decorator(parent, observer) );
828 }
829
830 void Decorator::SetBoundingBox( const Rect<int>& boundingBox )
831 {
832   mImpl->mBoundingBox = boundingBox;
833 }
834
835 const Rect<int>& Decorator::GetBoundingBox() const
836 {
837   return mImpl->mBoundingBox;
838 }
839
840 void Decorator::Relayout( const Vector2& size, const Vector2& scrollPosition )
841 {
842   mImpl->Relayout( size, scrollPosition );
843 }
844
845 /** Cursor **/
846
847 void Decorator::SetActiveCursor( ActiveCursor activeCursor )
848 {
849   mImpl->mActiveCursor = activeCursor;
850 }
851
852 unsigned int Decorator::GetActiveCursor() const
853 {
854   return mImpl->mActiveCursor;
855 }
856
857 void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight )
858 {
859   // Adjust grab handle displacement
860   mImpl->mGrabDisplacementX -= x - mImpl->mCursor[cursor].position.x;
861   mImpl->mGrabDisplacementY -= y - mImpl->mCursor[cursor].position.y;
862
863   mImpl->mCursor[cursor].position.x = x;
864   mImpl->mCursor[cursor].position.y = y;
865   mImpl->mCursor[cursor].cursorHeight = cursorHeight;
866   mImpl->mCursor[cursor].lineHeight = lineHeight;
867 }
868
869 void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const
870 {
871   x = mImpl->mCursor[cursor].position.x;
872   y = mImpl->mCursor[cursor].position.y;
873   cursorHeight = mImpl->mCursor[cursor].cursorHeight;
874   lineHeight = mImpl->mCursor[cursor].lineHeight;
875 }
876
877 void Decorator::SetColor( Cursor cursor, const Dali::Vector4& color )
878 {
879   mImpl->mCursor[cursor].color = color;
880 }
881
882 const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const
883 {
884   return mImpl->mCursor[cursor].color;
885 }
886
887 void Decorator::StartCursorBlink()
888 {
889   if ( !mImpl->mCursorBlinkTimer )
890   {
891     mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval );
892     mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick );
893   }
894
895   if ( !mImpl->mCursorBlinkTimer.IsRunning() )
896   {
897     mImpl->mCursorBlinkTimer.Start();
898   }
899 }
900
901 void Decorator::StopCursorBlink()
902 {
903   if ( mImpl->mCursorBlinkTimer )
904   {
905     mImpl->mCursorBlinkTimer.Stop();
906   }
907 }
908
909 void Decorator::SetCursorBlinkInterval( float seconds )
910 {
911   mImpl->mCursorBlinkInterval = static_cast<unsigned int>( seconds * TO_MILLISECONDS ); // Convert to milliseconds
912 }
913
914 float Decorator::GetCursorBlinkInterval() const
915 {
916   return static_cast<float>( mImpl->mCursorBlinkInterval ) * TO_SECONDS;
917 }
918
919 void Decorator::SetCursorBlinkDuration( float seconds )
920 {
921   mImpl->mCursorBlinkDuration = seconds;
922 }
923
924 float Decorator::GetCursorBlinkDuration() const
925 {
926   return mImpl->mCursorBlinkDuration;
927 }
928
929 /** GrabHandle **/
930
931 void Decorator::SetGrabHandleActive( bool active )
932 {
933   mImpl->mActiveGrabHandle = active;
934 }
935
936 bool Decorator::IsGrabHandleActive() const
937 {
938   return mImpl->mActiveGrabHandle;
939 }
940
941 void Decorator::SetGrabHandleImage( Dali::Image image )
942 {
943   mImpl->mGrabHandleImage = image;
944 }
945
946 Dali::Image Decorator::GetGrabHandleImage() const
947 {
948   return mImpl->mGrabHandleImage;
949 }
950
951 /** Selection **/
952
953 void Decorator::SetSelectionActive( bool active )
954 {
955   mImpl->mActiveSelection = active;
956 }
957
958 bool Decorator::IsSelectionActive() const
959 {
960   return mImpl->mActiveSelection;
961 }
962
963 void Decorator::SetPosition( SelectionHandle handle, float x, float y, float height )
964 {
965   mImpl->mSelectionHandle[handle].position.x = x;
966   mImpl->mSelectionHandle[handle].position.y = y;
967   mImpl->mSelectionHandle[handle].lineHeight = height;
968 }
969
970 void Decorator::GetPosition( SelectionHandle handle, float& x, float& y, float& height ) const
971 {
972   x = mImpl->mSelectionHandle[handle].position.x;
973   y = mImpl->mSelectionHandle[handle].position.y;
974   height = mImpl->mSelectionHandle[handle].lineHeight;
975 }
976
977 void Decorator::SetImage( SelectionHandle handle, SelectionHandleState state, Dali::Image image )
978 {
979   if( SELECTION_HANDLE_PRESSED == state )
980   {
981     mImpl->mSelectionHandle[handle].pressedImage = image;
982   }
983   else
984   {
985     mImpl->mSelectionHandle[handle].releasedImage = image;
986   }
987 }
988
989 Dali::Image Decorator::GetImage( SelectionHandle handle, SelectionHandleState state ) const
990 {
991   if( SELECTION_HANDLE_PRESSED == state )
992   {
993     return mImpl->mSelectionHandle[handle].pressedImage;
994   }
995
996   return mImpl->mSelectionHandle[handle].releasedImage;
997 }
998
999 void Decorator::AddHighlight( float x1, float y1, float x2, float y2 )
1000 {
1001   mImpl->mHighlightQuadList.push_back( QuadCoordinates(x1, y1, x2, y2) );
1002 }
1003
1004 void Decorator::ClearHighlights()
1005 {
1006   mImpl->mHighlightQuadList.clear();
1007 }
1008
1009 void Decorator::SetPopupActive( bool active )
1010 {
1011   mImpl->mActiveCopyPastePopup = active;
1012 }
1013
1014 bool Decorator::IsPopupActive() const
1015 {
1016   return mImpl->mActiveCopyPastePopup ;
1017 }
1018
1019 Decorator::~Decorator()
1020 {
1021   delete mImpl;
1022 }
1023
1024 Decorator::Decorator( Dali::Toolkit::Internal::Control& parent, Observer& observer )
1025 : mImpl( NULL )
1026 {
1027   mImpl = new Decorator::Impl( parent, observer );
1028 }
1029
1030 } // namespace Text
1031
1032 } // namespace Toolkit
1033
1034 } // namespace Dali