DALi Version 1.0.23
[platform/core/uifw/dali-toolkit.git] / base / dali-toolkit / internal / controls / text-input / text-input-text-highlight-impl.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-toolkit/internal/controls/text-input/text-input-text-highlight-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <math.h>
23 #include <sstream>
24 #include <algorithm>
25 #include <libintl.h>
26 #include <dali/integration-api/debug.h>
27
28 // INTERNAL INCLUDES
29
30 using namespace Dali;
31
32 namespace
33 {
34   /**
35    * Selection state enumeration (FSM)
36    */
37   enum SelectionState
38   {
39     SelectionNone,                            ///< Currently not encountered selected section.
40     SelectionStarted,                         ///< Encountered selected section
41     SelectionFinished                         ///< Finished selected section
42   };
43
44   const Vector4 LIGHTBLUE( 10.0f/255.0f, 140.0f/255.0f, 210.0f/255.0f, 1.0f );    // todo make this a setting
45
46   const float CHARACTER_THRESHOLD( 2.5f ); // todo check if unified method to do this in Text
47 }
48
49 namespace Dali
50 {
51
52 namespace Toolkit
53 {
54
55 namespace Internal
56 {
57
58 // Default constructor
59 TextHighlight::TextHighlight( TextViewCharacterPositioning& textViewCharacterPositioning ) :
60     mTextViewCharacterPositioning( textViewCharacterPositioning )
61 {
62 }
63
64 TextHighlight::~TextHighlight()
65 {
66 }
67
68 void TextHighlight::GetVisualTextSelection(std::vector<bool>& selectedVisualText, std::size_t startSelection, std::size_t endSelection,
69                                            Toolkit::TextView::TextLayoutInfo& textLayoutInfo )
70 {
71   std::vector<int>::iterator it = textLayoutInfo.mCharacterLogicalToVisualMap.begin();
72   std::vector<int>::iterator startSelectionIt = textLayoutInfo.mCharacterLogicalToVisualMap.begin() + std::min(startSelection, endSelection);
73   std::vector<int>::iterator endSelectionIt = textLayoutInfo.mCharacterLogicalToVisualMap.begin() + std::max(startSelection, endSelection);
74   std::vector<int>::iterator end = textLayoutInfo.mCharacterLogicalToVisualMap.end();
75
76   selectedVisualText.resize( mTextViewCharacterPositioning.GetNumberOfCharactersInText() );
77
78   // Deselect text prior to startSelectionIt
79   for(;it!=startSelectionIt;++it)
80   {
81     selectedVisualText[*it] = false;
82   }
83
84   // Select text from startSelectionIt -> endSelectionIt
85   for(;it!=endSelectionIt;++it)
86   {
87     selectedVisualText[*it] = true;
88   }
89
90   // Deselect text after endSelection
91   for(;it!=end;++it)
92   {
93     selectedVisualText[*it] = false;
94   }
95
96   selectedVisualText.resize( mTextViewCharacterPositioning.GetNumberOfCharactersInText(), false );
97 }
98
99 // Calculate the dimensions of the quads they will make the highlight mesh
100 TextHighlight::HighlightInfo TextHighlight::CalculateHighlightInfo( std::size_t handlePositionStart, std::size_t handlePositionEnd, Toolkit::TextView::TextLayoutInfo& textLayoutInfo )
101 {
102   // At the moment there is no public API to modify the block alignment option.
103
104   TextHighlight::HighlightInfo newHighlightInfo;
105   //newHighlightInfo.mQuadList.clear(); // clear last quad information.
106
107   if ( !mTextViewCharacterPositioning.IsTextEmpty() && !textLayoutInfo.mCharacterLogicalToVisualMap.empty() )
108   {
109     // Get vector of flags representing characters that are selected (true) vs unselected (false).
110     std::vector<bool> selectedVisualText;
111     GetVisualTextSelection(selectedVisualText, handlePositionStart, handlePositionEnd, textLayoutInfo );
112     std::vector<bool>::iterator selectedIt(selectedVisualText.begin());
113     std::vector<bool>::iterator selectedEndIt(selectedVisualText.end());
114
115     SelectionState selectionState = SelectionNone;          ///< Current selection status of cursor over entire text.
116     float rowLeft = 0.0f;
117     float rowRight = 0.0f;
118     // Keep track of the TextView's min/max extents. Should be able to query this from TextView.
119     float maxRowLeft = std::numeric_limits<float>::max();
120     float maxRowRight = 0.0f;
121
122     Toolkit::TextView::CharacterLayoutInfoContainer::iterator it = textLayoutInfo.mCharacterLayoutInfoTable.begin();
123     Toolkit::TextView::CharacterLayoutInfoContainer::iterator end = textLayoutInfo.mCharacterLayoutInfoTable.end();
124
125     Toolkit::TextView::CharacterLayoutInfoContainer::iterator lastIt = it;
126
127     // Scan through entire text.
128     while(it != end)
129     {
130       // selectionState: None when not in selection, Started when in selection, and Ended when reached end of selection.
131
132       Toolkit::TextView::CharacterLayoutInfo& charInfo(*it);
133       bool charSelected( false );
134       if( selectedIt != selectedEndIt )
135       {
136         charSelected = *selectedIt++;
137       }
138
139       if(selectionState == SelectionNone)
140       {
141         if(charSelected)
142         {
143           selectionState = SelectionStarted;
144           rowLeft = charInfo.mPosition.x - textLayoutInfo.mScrollOffset.x;
145           rowRight = rowLeft + charInfo.mSize.width;
146         }
147       }
148       else if(selectionState == SelectionStarted)
149       {
150         // break selection on:
151         // 1. new line causing selection break. (\n or wordwrap)
152         // 2. character not selected.
153         if(charInfo.mPosition.y - lastIt->mPosition.y > CHARACTER_THRESHOLD ||
154            !charSelected)
155         {
156           // finished selection.
157           // TODO: TextView should have a table of visual rows, and each character a reference to the row
158           // that it resides on. That way this enumeration is not necessary.
159           Vector2 min, max;
160           if(lastIt->mIsNewParagraphChar)
161           {
162             // If the last character is a new line, then to get the row rect, we need to scan from the character before the new line.
163             lastIt = std::max( textLayoutInfo.mCharacterLayoutInfoTable.begin(), lastIt - 1 );
164           }
165           const Size rowSize( mTextViewCharacterPositioning.GetRowRectFromCharacterPosition( lastIt - textLayoutInfo.mCharacterLayoutInfoTable.begin(), min, max ) );
166           maxRowLeft = std::min(maxRowLeft, min.x);
167           maxRowRight = std::max(maxRowRight, max.x);
168           float rowBottom = lastIt->mPosition.y - textLayoutInfo.mScrollOffset.y;
169           float rowTop = rowBottom - rowSize.height;
170
171           // Still selected, and block-align mode then set rowRight to max, so it can be clamped afterwards
172           if(charSelected)
173           {
174             rowRight = std::numeric_limits<float>::max();
175           }
176           newHighlightInfo.AddQuad( rowLeft, rowTop, rowRight, rowBottom );
177
178           selectionState = SelectionNone;
179
180           // Still selected? start a new selection
181           if( charSelected )
182           {
183             // if block-align mode then set rowLeft to min, so it can be clamped afterwards
184             rowLeft = 0.0f;
185             rowRight = ( charInfo.mPosition.x - textLayoutInfo.mScrollOffset.x ) + charInfo.mSize.width;
186             selectionState = SelectionStarted;
187           }
188         }
189         else
190         {
191           // build up highlight(s) with this selection data.
192           rowLeft = std::min( charInfo.mPosition.x - textLayoutInfo.mScrollOffset.x, rowLeft );
193           rowRight = std::max( ( charInfo.mPosition.x - textLayoutInfo.mScrollOffset.x ) + charInfo.mSize.width, rowRight );
194         }
195       }
196
197       lastIt = it++;
198     }
199
200     // If reached end, and still on selection, then close selection.
201     if(it == end)
202     {
203       if(selectionState == SelectionStarted)
204       {
205         // finished selection.
206         Vector2 min, max;
207         if(lastIt != end && lastIt->mIsNewParagraphChar)
208         {
209           lastIt = std::max( textLayoutInfo.mCharacterLayoutInfoTable.begin(), lastIt - 1 );
210         }
211         if( lastIt != end )
212         {
213           const Size rowSize( mTextViewCharacterPositioning.GetRowRectFromCharacterPosition( lastIt - textLayoutInfo.mCharacterLayoutInfoTable.begin(), min, max ) );
214           maxRowLeft = std::min(maxRowLeft, min.x);
215           maxRowRight = std::max(maxRowRight, max.x);
216           float rowBottom = lastIt->mPosition.y - textLayoutInfo.mScrollOffset.y;
217           float rowTop = rowBottom - rowSize.height;
218           newHighlightInfo.AddQuad( rowLeft, rowTop, rowRight, rowBottom );
219         }
220       }
221     }
222
223     // Get the top left and bottom right corners.
224     const Toolkit::TextView::CharacterLayoutInfo& firstCharacter( *textLayoutInfo.mCharacterLayoutInfoTable.begin() );
225     const Vector2 topLeft( maxRowLeft, firstCharacter.mPosition.y - firstCharacter.mSize.height );
226     const Vector2 bottomRight( topLeft.x + textLayoutInfo.mTextSize.width, topLeft.y + textLayoutInfo.mTextSize.height );
227
228     // Clamp quads so they appear to clip to borders of the whole text.
229     newHighlightInfo.Clamp2D( topLeft, bottomRight );
230
231     // For block-align align Further Clamp quads to max left and right extents
232       // BlockAlign: Will adjust highlight to block:
233       // i.e.
234       //   H[ello] (top row right = max of all rows right)
235       // [--this-] (middle rows' left = min of all rows left, middle rows' right = max of all rows right)
236       // [is some] (middle rows' left = min of all rows left, middle rows' right = max of all rows right)
237       // [text] (bottom row left = min of all rows left)
238       // (common in SMS messaging selection)
239       //
240       // As opposed to the default which is tight text highlighting.
241       //   H[ello]
242       //   [this]
243       // [is some]
244       // [text]
245       // (common in regular text editors/web browser selection)
246       newHighlightInfo.Clamp2D( Vector2(maxRowLeft, topLeft.y), Vector2(maxRowRight, bottomRight.y ) );
247
248   }
249
250   return newHighlightInfo;
251 }
252
253 void TextHighlight::UpdateHighlight( TextHighlight::HighlightInfo& newHighlightInfo )
254 {
255 //  Construct a Mesh with a texture to be used as the highlight 'box' for selected text
256 //
257 //  Example scenarios where mesh is made from 3, 1, 2, 2 ,3 or 3 quads.
258 //
259 //   [ TOP   ]  [ TOP ]      [TOP ]  [ TOP    ]      [ TOP  ]      [ TOP  ]
260 //  [ MIDDLE ]             [BOTTOM]  [BOTTOM]      [ MIDDLE ]   [ MIDDLE  ]
261 //  [ BOTTOM]                                      [ MIDDLE ]   [ MIDDLE  ]
262 //                                                 [BOTTOM]     [ MIDDLE  ]
263 //                                                              [BOTTOM]
264 //
265 //  Each quad is created as 2 triangles.
266 //  Middle is just 1 quad regardless of its size.
267 //
268 //  (0,0)         (0,0)
269 //     0*    *2     0*       *2
270 //     TOP          TOP
271 //     3*    *1     3*       *1
272 //  4*       *1     4*     *6
273 //     MIDDLE         BOTTOM
274 //  6*       *5     7*     *5
275 //  6*    *8
276 //   BOTTOM
277 //  9*    *7
278 //
279
280   // vertex and triangle buffers should always be present if MeshActor is alive.
281   //HighlightInfo newHighlightInfo = CalculateHighlightInfo( handlePositionStart, handlePositionEnd );
282   MeshData::VertexContainer vertices;
283   Dali::MeshData::FaceIndices faceIndices;
284
285   if( !newHighlightInfo.mQuadList.empty() )
286   {
287     std::vector<QuadCoordinates>::iterator iter = newHighlightInfo.mQuadList.begin();
288     std::vector<QuadCoordinates>::iterator endIter = newHighlightInfo.mQuadList.end();
289
290     // vertex position defaults to (0 0 0)
291     MeshData::Vertex vertex;
292     // set normal for all vertices as (0 0 1) pointing outward from TextInput Actor.
293     vertex.nZ = 1.0f;
294
295     for(std::size_t v = 0; iter != endIter; ++iter,v+=4 )
296     {
297       // Add each quad geometry (a sub-selection) to the mesh data.
298
299       // 0-----1
300       // |\    |
301       // | \ A |
302       // |  \  |
303       // | B \ |
304       // |    \|
305       // 2-----3
306
307       QuadCoordinates& quad = *iter;
308       // top-left (v+0)
309       vertex.x = quad.min.x;
310       vertex.y = quad.min.y;
311       vertices.push_back( vertex );
312
313       // top-right (v+1)
314       vertex.x = quad.max.x;
315       vertex.y = quad.min.y;
316       vertices.push_back( vertex );
317
318       // bottom-left (v+2)
319       vertex.x = quad.min.x;
320       vertex.y = quad.max.y;
321       vertices.push_back( vertex );
322
323       // bottom-right (v+3)
324       vertex.x = quad.max.x;
325       vertex.y = quad.max.y;
326       vertices.push_back( vertex );
327
328       // triangle A (3, 1, 0)
329       faceIndices.push_back( v + 3 );
330       faceIndices.push_back( v + 1 );
331       faceIndices.push_back( v );
332
333       // triangle B (0, 2, 3)
334       faceIndices.push_back( v );
335       faceIndices.push_back( v + 2 );
336       faceIndices.push_back( v + 3 );
337     }
338
339     mMeshData.SetVertices( vertices );
340     mMeshData.SetFaceIndices( faceIndices );
341
342     mHighlightMesh.UpdateMeshData(mMeshData);
343   }
344 }
345
346 Mesh TextHighlight::CreateHighLightMesh()
347 {
348   mMeshData = MeshData( );
349   mMeshData.SetHasNormals( true );
350
351   mCustomMaterial = Material::New("CustomMaterial");
352   mCustomMaterial.SetDiffuseColor( LIGHTBLUE );
353
354   mMeshData.SetMaterial( mCustomMaterial );
355
356   mHighlightMesh = Mesh::New( mMeshData );
357
358   return mHighlightMesh;
359 }
360
361 void TextHighlight::HighlightInfo::AddQuad( float x1, float y1, float x2, float y2 )
362 {
363   QuadCoordinates quad(x1, y1, x2, y2);
364   mQuadList.push_back( quad );
365 }
366
367 void TextHighlight::HighlightInfo::Clamp2D(const Vector2& min, const Vector2& max)
368 {
369   for(std::size_t i = 0;i < mQuadList.size(); i++)
370   {
371     QuadCoordinates& quad = mQuadList[i];
372
373     quad.min.Clamp(min, max);
374     quad.max.Clamp(min, max);
375   }
376 }
377
378 } // Internal
379
380 } // namespace Toolkit
381
382 } // namespace Dali
383