Copied some TextInput grab/selection handle code
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / public-api / text / text-controller.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/public-api/text/text-controller.h>
20
21 // INTERNAL INCLUDES
22 #include <dali-toolkit/public-api/text/character-set-conversion.h>
23 #include <dali-toolkit/public-api/text/layouts/layout-engine.h>
24 #include <dali-toolkit/public-api/text/logical-model.h>
25 #include <dali-toolkit/public-api/text/multi-language-support.h>
26 #include <dali-toolkit/public-api/text/script-run.h>
27 #include <dali-toolkit/public-api/text/segmentation.h>
28 #include <dali-toolkit/public-api/text/shaper.h>
29 #include <dali-toolkit/public-api/text/text-view.h>
30 #include <dali-toolkit/public-api/text/visual-model.h>
31
32 // EXTERNAL INCLUDES
33 #include <limits>
34 #include <vector>
35 #include <dali/public-api/text-abstraction/font-client.h>
36
37 using std::vector;
38
39 namespace Dali
40 {
41
42 namespace Toolkit
43 {
44
45 namespace Text
46 {
47
48 struct Controller::TextInput
49 {
50   // Used to queue input events until DoRelayout()
51   enum EventType
52   {
53     KEYBOARD_FOCUS_GAIN_EVENT,
54     KEYBOARD_FOCUS_LOST_EVENT,
55     TAP_EVENT,
56     GRAB_HANDLE_EVENT
57   };
58
59   union Param
60   {
61     int mInt;
62     unsigned int mUint;
63     float mFloat;
64   };
65
66   struct Event
67   {
68     Event( EventType eventType )
69     : type( eventType )
70     {
71       p1.mInt = 0;
72       p2.mInt = 0;
73     }
74
75     EventType type;
76     Param p1;
77     Param p2;
78     Param p3;
79   };
80
81   enum State
82   {
83     INACTIVE,
84     SELECTING,
85     EDITING
86   };
87
88   TextInput( DecoratorPtr decorator )
89   : mDecorator( decorator ),
90     mState( INACTIVE )
91   {
92   }
93
94   /**
95    * @brief Helper to move the cursor, grab handle etc.
96    */
97   bool ProcessTouchEvents()
98   {
99     mDecoratorUpdated = false;
100
101     if( mDecorator )
102     {
103       for( vector<TextInput::Event>::iterator iter = mEventQueue.begin(); iter != mEventQueue.end(); ++iter )
104       {
105         switch( iter->type )
106         {
107           case KEYBOARD_FOCUS_GAIN_EVENT:
108           {
109             OnKeyboardFocus( true );
110             break;
111           }
112           case KEYBOARD_FOCUS_LOST_EVENT:
113           {
114             OnKeyboardFocus( false );
115             break;
116           }
117           case TAP_EVENT:
118           {
119             OnTapEvent( *iter );
120             break;
121           }
122           case GRAB_HANDLE_EVENT:
123           {
124             OnGrabHandleEvent( *iter );
125             break;
126           }
127         }
128       }
129     }
130
131     mEventQueue.clear();
132
133     return mDecoratorUpdated;
134   }
135
136   void OnKeyboardFocus( bool hasFocus )
137   {
138     // TODO
139   }
140
141   void OnTapEvent( const Event& event )
142   {
143     if( 1u == event.p1.mUint )
144     {
145       mState = TextInput::EDITING;
146       mDecorator->SetGrabHandleActive( true );
147       mDecorator->SetPosition( PRIMARY_CURSOR, 0, 0, 10 );
148       mDecoratorUpdated = true;
149     }
150     else if( 2u == event.p1.mUint )
151     {
152       mState = TextInput::SELECTING;
153       mDecorator->SetGrabHandleActive( false );
154       mDecorator->SetSelectionActive( true );
155       mDecoratorUpdated = true;
156     }
157   }
158
159   void OnGrabHandleEvent( const Event& event )
160   {
161     // TODO
162   }
163
164   DecoratorPtr mDecorator;
165   bool mDecoratorUpdated;
166
167   State mState;
168
169   /**
170    * This is used to delay handling events until after the model has been updated.
171    * The number of updates to the model is minimized to improve performance.
172    */
173   vector<Event> mEventQueue; ///< The queue of touch events etc.
174 };
175
176 struct Controller::Impl
177 {
178   Impl( ControlInterface& controlInterface )
179   : mControlInterface( controlInterface ),
180     mNewText(),
181     mOperations( NO_OPERATION ),
182     mControlSize(),
183     mTextInput( NULL )
184   {
185     mLogicalModel = LogicalModel::New();
186     mVisualModel  = VisualModel::New();
187
188     mView.SetVisualModel( mVisualModel );
189
190     mFontClient = TextAbstraction::FontClient::Get();
191   }
192
193   ~Impl()
194   {
195     delete mTextInput;
196   }
197
198   ControlInterface& mControlInterface;
199
200   std::string mNewText;
201
202   LogicalModelPtr mLogicalModel;
203   VisualModelPtr  mVisualModel;
204
205   View mView;
206
207   LayoutEngine mLayoutEngine;
208
209   TextAbstraction::FontClient mFontClient;
210
211   OperationsMask mOperations;
212
213   Size mControlSize;
214
215   // Avoid allocating everything for text input until EnableTextInput()
216   Controller::TextInput* mTextInput;
217 };
218
219 ControllerPtr Controller::New( ControlInterface& controlInterface )
220 {
221   return ControllerPtr( new Controller( controlInterface ) );
222 }
223
224 void Controller::SetText( const std::string& text )
225 {
226   // Keep until size negotiation
227   mImpl->mNewText = text;
228   mImpl->mOperations = ALL_OPERATIONS;
229
230   if( mImpl->mTextInput )
231   {
232     // Cancel previously queued events
233     mImpl->mTextInput->mEventQueue.clear();
234
235     // TODO - Hide selection decorations
236   }
237 }
238
239 void Controller::EnableTextInput( DecoratorPtr decorator )
240 {
241   if( !mImpl->mTextInput )
242   {
243     mImpl->mTextInput = new TextInput( decorator );
244   }
245 }
246
247 bool Controller::Relayout( const Vector2& size )
248 {
249   if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
250   {
251     // Not worth to relayout if width or height is equal to zero.
252     return false;
253   }
254
255   bool updated = false;
256
257   if( size != mImpl->mControlSize )
258   {
259     updated = DoRelayout( size, mImpl->mOperations );
260
261     // Do not re-do any operation until something changes.
262     mImpl->mOperations = NO_OPERATION;
263
264     mImpl->mControlSize = size;
265   }
266
267   if( mImpl->mTextInput )
268   {
269     // Move the cursor, grab handle etc.
270     updated = mImpl->mTextInput->ProcessTouchEvents() || updated;
271   }
272
273   return updated;
274 }
275
276 bool Controller::DoRelayout( const Vector2& size, OperationsMask operations )
277 {
278   bool viewUpdated( false );
279
280   Vector<Character> utf32Characters;
281   Length characterCount = 0u;
282   if( CONVERT_TO_UTF32 & operations )
283   {
284     std::string& text = mImpl->mNewText;
285
286     //  Convert text into UTF-32
287     utf32Characters.Resize( text.size() );
288
289     // This is a bit horrible but std::string returns a (signed) char*
290     const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
291
292     // Transform a text array encoded in utf8 into an array encoded in utf32.
293     // It returns the actual number of characters.
294     characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
295     utf32Characters.Resize( characterCount );
296
297     // Sets the text into the model.
298     mImpl->mLogicalModel->SetText( utf32Characters.Begin(), characterCount );
299
300     // Discard temporary text
301     text.clear();
302   }
303
304   Vector<LineBreakInfo> lineBreakInfo;
305   if( GET_LINE_BREAKS & operations )
306   {
307     // Retrieves the line break info. The line break info is used to split the text in 'paragraphs' to
308     // calculate the bidirectional info for each 'paragraph'.
309     // It's also used to layout the text (where it should be a new line) or to shape the text (text in different lines
310     // is not shaped together).
311     lineBreakInfo.Resize( characterCount, TextAbstraction::LINE_NO_BREAK );
312
313     SetLineBreakInfo( utf32Characters,
314                       lineBreakInfo );
315
316     mImpl->mLogicalModel->SetLineBreakInfo( lineBreakInfo.Begin(), characterCount );
317   }
318
319   const bool getScripts = GET_SCRIPTS & operations;
320   const bool validateFonts = VALIDATE_FONTS & operations;
321
322   Vector<ScriptRun> scripts;
323   Vector<FontRun> fonts;
324   if( getScripts || validateFonts )
325   {
326     // Validates the fonts assigned by the application or assigns default ones.
327     // It makes sure all the characters are going to be rendered by the correct font.
328     MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
329
330     if( getScripts )
331     {
332       // Retrieves the scripts used in the text.
333       multilanguageSupport.SetScripts( utf32Characters,
334                                        lineBreakInfo,
335                                        scripts );
336
337       // Sets the scripts into the model.
338       mImpl->mLogicalModel->SetScripts( scripts.Begin(), scripts.Count() );
339     }
340
341     if( validateFonts )
342     {
343       // Validates the fonts. If there is a character with no assigned font it sets a default one.
344       // After this call, fonts are validated.
345       multilanguageSupport.ValidateFonts( utf32Characters,
346                                           scripts,
347                                           fonts );
348
349       // Sets the fonts into the model.
350       mImpl->mLogicalModel->SetFonts( fonts.Begin(), fonts.Count() );
351     }
352   }
353
354   Vector<GlyphInfo> glyphs;
355   Vector<CharacterIndex> characterIndices;
356   Vector<Length> charactersPerGlyph;
357   if( SHAPE_TEXT & operations )
358   {
359     // Shapes the text.
360     ShapeText( utf32Characters,
361                lineBreakInfo,
362                scripts,
363                fonts,
364                glyphs,
365                characterIndices,
366                charactersPerGlyph );
367   }
368
369   if( GET_GLYPH_METRICS & operations )
370   {
371     TextAbstraction::FontClient::Get().GetGlyphMetrics( glyphs.Begin(), glyphs.Count() );
372   }
373
374   if( LAYOUT & operations )
375   {
376     if( 0u == glyphs.Count() )
377     {
378       const Length numberOfGlyphs = mImpl->mVisualModel->GetNumberOfGlyphs();
379
380       glyphs.Resize( numberOfGlyphs );
381       characterIndices.Resize( numberOfGlyphs );
382       charactersPerGlyph.Resize( numberOfGlyphs );
383
384       mImpl->mVisualModel->GetGlyphs( glyphs.Begin(),
385                                       0u,
386                                       numberOfGlyphs );
387
388       mImpl->mVisualModel->GetGlyphToCharacterMap( characterIndices.Begin(),
389                                                    0u,
390                                                    numberOfGlyphs );
391
392       mImpl->mVisualModel->GetCharactersPerGlyphMap( charactersPerGlyph.Begin(),
393                                                      0u,
394                                                      numberOfGlyphs );
395     }
396
397     // Update the visual model
398     mImpl->mLayoutEngine.UpdateVisualModel( size,
399                                             glyphs,
400                                             characterIndices,
401                                             charactersPerGlyph,
402                                             *mImpl->mVisualModel );
403
404     viewUpdated = true;
405   }
406
407   return viewUpdated;
408 }
409
410 Vector3 Controller::GetNaturalSize()
411 {
412   // Operations that can be done only once until the text changes.
413   const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
414                                                                          GET_SCRIPTS      |
415                                                                          VALIDATE_FONTS   |
416                                                                          GET_LINE_BREAKS  |
417                                                                          GET_WORD_BREAKS  |
418                                                                          SHAPE_TEXT       |
419                                                                          GET_GLYPH_METRICS );
420
421   // Operations that need to be done if the size or the text changes.
422   const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
423                                                                       REORDER );
424
425   const float maxFloat = std::numeric_limits<float>::max();
426   DoRelayout( Vector2( maxFloat, maxFloat ),
427               static_cast<OperationsMask>( onlyOnceOperations |
428                                            sizeOperations ) );
429
430   // Do not do again the only once operations.
431   mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations & ~onlyOnceOperations );
432
433   // Do the size related operations again.
434   mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations | sizeOperations );
435
436   return Vector3( mImpl->mVisualModel->GetNaturalSize() );
437 }
438
439 float Controller::GetHeightForWidth( float width )
440 {
441   // Operations that can be done only once until the text changes.
442   const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
443                                                                          GET_SCRIPTS      |
444                                                                          VALIDATE_FONTS   |
445                                                                          GET_LINE_BREAKS  |
446                                                                          GET_WORD_BREAKS  |
447                                                                          SHAPE_TEXT       |
448                                                                          GET_GLYPH_METRICS );
449
450   // Operations that need to be done if the size or the text changes.
451   const OperationsMask sizeOperations =  static_cast<OperationsMask>( LAYOUT |
452                                                                       REORDER );
453
454   DoRelayout( Size( width, 0.f ),
455               static_cast<OperationsMask>( onlyOnceOperations |
456                                            sizeOperations ) );
457
458   // Do not do again the only once operations.
459   mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations & ~onlyOnceOperations );
460
461   // Do the size related operations again.
462   mImpl->mOperations = static_cast<OperationsMask>( mImpl->mOperations | sizeOperations );
463
464   return mImpl->mVisualModel->GetActualSize().height;
465 }
466
467 View& Controller::GetView()
468 {
469   return mImpl->mView;
470 }
471
472 LayoutEngine& Controller::GetLayoutEngine()
473 {
474   return mImpl->mLayoutEngine;
475 }
476
477 void Controller::RequestRelayout()
478 {
479   mImpl->mControlInterface.RequestTextRelayout();
480 }
481
482 void Controller::KeyboardFocusGainEvent()
483 {
484   DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyboardFocusGainEvent" );
485
486   if( mImpl->mTextInput )
487   {
488     TextInput::Event event( TextInput::KEYBOARD_FOCUS_GAIN_EVENT );
489     mImpl->mTextInput->mEventQueue.push_back( event );
490
491     RequestRelayout();
492   }
493 }
494
495 void Controller::KeyboardFocusLostEvent()
496 {
497   DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyboardFocusLostEvent" );
498
499   if( mImpl->mTextInput )
500   {
501     TextInput::Event event( TextInput::KEYBOARD_FOCUS_LOST_EVENT );
502     mImpl->mTextInput->mEventQueue.push_back( event );
503
504     RequestRelayout();
505   }
506 }
507
508 void Controller::TapEvent( unsigned int tapCount, float x, float y )
509 {
510   DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected TapEvent" );
511
512   if( mImpl->mTextInput )
513   {
514     TextInput::Event event( TextInput::TAP_EVENT );
515     event.p1.mUint = tapCount;
516     event.p2.mFloat = x;
517     event.p3.mFloat = y;
518     mImpl->mTextInput->mEventQueue.push_back( event );
519
520     RequestRelayout();
521   }
522 }
523
524 void Controller::GrabHandleEvent( GrabHandleState state, float x )
525 {
526   DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected GrabHandleEvent" );
527
528   if( mImpl->mTextInput )
529   {
530     TextInput::Event event( TextInput::GRAB_HANDLE_EVENT );
531     event.p1.mInt   = state;
532     event.p2.mFloat = x;
533     mImpl->mTextInput->mEventQueue.push_back( event );
534
535     RequestRelayout();
536   }
537 }
538
539 Controller::~Controller()
540 {
541   delete mImpl;
542 }
543
544 Controller::Controller( ControlInterface& controlInterface )
545 : mImpl( NULL )
546 {
547   mImpl = new Controller::Impl( controlInterface );
548 }
549
550 } // namespace Text
551
552 } // namespace Toolkit
553
554 } // namespace Dali