UTC added for Text, CharacterSetConversion.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller-impl.h
1 #ifndef __DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H__
2 #define __DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H__
3
4 /*
5  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/text-abstraction/font-client.h>
23 #include <dali/devel-api/adaptor-framework/imf-manager.h>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
27 #include <dali-toolkit/internal/text/logical-model-impl.h>
28 #include <dali-toolkit/internal/text/text-controller.h>
29 #include <dali-toolkit/internal/text/visual-model-impl.h>
30
31 namespace Dali
32 {
33
34 namespace Toolkit
35 {
36
37 namespace Text
38 {
39
40 struct Event
41 {
42   // Used to queue input events until DoRelayout()
43   enum Type
44   {
45     CURSOR_KEY_EVENT,
46     TAP_EVENT,
47     PAN_EVENT,
48     GRAB_HANDLE_EVENT,
49     LEFT_SELECTION_HANDLE_EVENT,
50     RIGHT_SELECTION_HANDLE_EVENT
51   };
52
53   union Param
54   {
55     int mInt;
56     unsigned int mUint;
57     float mFloat;
58   };
59
60   Event( Type eventType )
61   : type( eventType )
62   {
63     p1.mInt = 0;
64     p2.mInt = 0;
65     p3.mInt = 0;
66   }
67
68   Type type;
69   Param p1;
70   Param p2;
71   Param p3;
72 };
73
74 struct CursorInfo
75 {
76   CursorInfo()
77   : primaryPosition(),
78     secondaryPosition(),
79     lineHeight( 0.f ),
80     primaryCursorHeight( 0.f ),
81     secondaryCursorHeight( 0.f ),
82     isSecondaryCursor( false )
83   {}
84
85   ~CursorInfo()
86   {}
87
88   Vector2 primaryPosition;       ///< The primary cursor's position.
89   Vector2 secondaryPosition;     ///< The secondary cursor's position.
90   float   lineHeight;            ///< The height of the line where the cursor is placed.
91   float   primaryCursorHeight;   ///< The primary cursor's height.
92   float   secondaryCursorHeight; ///< The secondary cursor's height.
93   bool    isSecondaryCursor;     ///< Whether the secondary cursor is valid.
94 };
95
96 struct EventData
97 {
98   enum State
99   {
100     INACTIVE,
101     SELECTING,
102     EDITING,
103     EDITING_WITH_POPUP
104   };
105
106   EventData( DecoratorPtr decorator );
107
108   ~EventData();
109
110   DecoratorPtr       mDecorator;               ///< Pointer to the decorator
111   std::string        mPlaceholderTextActive;   ///< The text to display when the TextField is empty with key-input focus
112   std::string        mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive
113   Vector4            mPlaceholderTextColor;    ///< The in/active placeholder text color
114
115   /**
116    * This is used to delay handling events until after the model has been updated.
117    * The number of updates to the model is minimized to improve performance.
118    */
119   std::vector<Event> mEventQueue;              ///< The queue of touch events etc.
120
121   /**
122    * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
123    * Typically this will have a negative value with scrolling occurs.
124    */
125   Vector2            mScrollPosition;          ///< The text is offset by this position when scrolling.
126
127   State              mState;                   ///< Selection mode, edit mode etc.
128
129   CharacterIndex     mPrimaryCursorPosition;   ///< Index into logical model for primary cursor.
130   CharacterIndex     mLeftSelectionPosition;   ///< Index into logical model for left selection handle.
131   CharacterIndex     mRightSelectionPosition;  ///< Index into logical model for right selection handle.
132
133   CharacterIndex     mPreEditStartPosition;    ///< Used to remove the pre-edit text if necessary.
134   Length             mPreEditLength;           ///< Used to remove the pre-edit text if necessary.
135
136   bool mIsShowingPlaceholderText           : 1;   ///< True if the place-holder text is being displayed.
137   bool mPreEditFlag                        : 1;   ///< True if the model contains text in pre-edit state.
138   bool mDecoratorUpdated                   : 1;   ///< True if the decorator was updated during event processing.
139   bool mCursorBlinkEnabled                 : 1;   ///< True if cursor should blink when active.
140   bool mGrabHandleEnabled                  : 1;   ///< True if grab handle is enabled.
141   bool mGrabHandlePopupEnabled             : 1;   ///< True if the grab handle popu-up should be shown.
142   bool mSelectionEnabled                   : 1;   ///< True if selection handles, highlight etc. are enabled.
143   bool mHorizontalScrollingEnabled         : 1;   ///< True if horizontal scrolling is enabled.
144   bool mVerticalScrollingEnabled           : 1;   ///< True if vertical scrolling is enabled.
145   bool mUpdateCursorPosition               : 1;   ///< True if the visual position of the cursor must be recalculated.
146   bool mUpdateLeftSelectionPosition        : 1;   ///< True if the visual position of the left selection handle must be recalculated.
147   bool mUpdateRightSelectionPosition       : 1;   ///< True if the visual position of the right selection handle must be recalculated.
148   bool mScrollAfterUpdateCursorPosition    : 1;   ///< Whether to scroll after the cursor position is updated.
149   bool mScrollAfterDelete                  : 1;   ///< Whether to scroll after delete characters.
150 };
151
152 struct ModifyEvent
153 {
154   enum Type
155   {
156     TEXT_REPLACED,    ///< The entire text was replaced
157     TEXT_INSERTED,    ///< Insert characters at the current cursor position
158     TEXT_DELETED      ///< Characters were deleted
159   };
160
161   Type type;
162 };
163
164 struct FontDefaults
165 {
166   FontDefaults()
167   : mDefaultPointSize(0.0f),
168     mFontId(0u)
169   {
170   }
171
172   FontId GetFontId( TextAbstraction::FontClient& fontClient )
173   {
174     if( !mFontId )
175     {
176       Dali::TextAbstraction::PointSize26Dot6 pointSize = mDefaultPointSize*64;
177       mFontId = fontClient.GetFontId( mDefaultFontFamily, mDefaultFontStyle, pointSize );
178     }
179
180     return mFontId;
181   }
182
183   std::string mDefaultFontFamily;
184   std::string mDefaultFontStyle;
185   float mDefaultPointSize;
186   FontId mFontId;
187 };
188
189 struct Controller::Impl
190 {
191   Impl( ControlInterface& controlInterface )
192   : mControlInterface( controlInterface ),
193     mLogicalModel(),
194     mVisualModel(),
195     mFontDefaults( NULL ),
196     mEventData( NULL ),
197     mFontClient(),
198     mView(),
199     mLayoutEngine(),
200     mModifyEvents(),
201     mControlSize(),
202     mTextColor( Color::BLACK ),
203     mAlignmentOffset(),
204     mOperationsPending( NO_OPERATION ),
205     mMaximumNumberOfCharacters( 50 ),
206     mRecalculateNaturalSize( true )
207   {
208     mLogicalModel = LogicalModel::New();
209     mVisualModel  = VisualModel::New();
210
211     mFontClient = TextAbstraction::FontClient::Get();
212
213     mView.SetVisualModel( mVisualModel );
214
215     // Set the text properties to default
216     mVisualModel->SetUnderlineEnabled( false );
217     mVisualModel->SetUnderlineHeight( 0.0f );
218   }
219
220   ~Impl()
221   {
222     delete mEventData;
223   }
224
225   /**
226    * @brief Request a relayout using the ControlInterface.
227    */
228   void RequestRelayout();
229
230   /**
231    * @brief Request a relayout using the ControlInterface.
232    */
233   void QueueModifyEvent( ModifyEvent::Type type )
234   {
235     if( ModifyEvent::TEXT_REPLACED == type)
236     {
237       // Cancel previously queued inserts etc.
238       mModifyEvents.clear();
239     }
240
241     ModifyEvent event;
242     event.type = type;
243     mModifyEvents.push_back( event );
244
245     // The event will be processed during relayout
246     RequestRelayout();
247   }
248
249   /**
250    * @brief Helper to move the cursor, grab handle etc.
251    */
252   bool ProcessInputEvents();
253
254   /**
255    * @brief Helper to check whether any place-holder text is available.
256    */
257   bool IsPlaceholderAvailable() const
258   {
259     return ( mEventData &&
260              ( !mEventData->mPlaceholderTextInactive.empty() ||
261                !mEventData->mPlaceholderTextActive.empty() )
262            );
263   }
264
265   bool IsShowingPlaceholderText() const
266   {
267     return ( mEventData && mEventData->mIsShowingPlaceholderText );
268   }
269
270   /**
271    * @brief Called when placeholder-text is hidden
272    */
273   void PlaceholderCleared()
274   {
275     if( mEventData )
276     {
277       mEventData->mIsShowingPlaceholderText = false;
278
279       // Remove mPlaceholderTextColor
280       mVisualModel->SetTextColor( mTextColor );
281     }
282   }
283
284   void ClearPreEditFlag()
285   {
286     if( mEventData )
287     {
288       mEventData->mPreEditFlag = false;
289       mEventData->mPreEditStartPosition = 0;
290       mEventData->mPreEditLength = 0;
291     }
292   }
293
294   void ResetImfManager()
295   {
296     // Reset incase we are in a pre-edit state.
297     ImfManager imfManager = ImfManager::Get();
298     if ( imfManager )
299     {
300       imfManager.Reset(); // Will trigger a commit message
301     }
302
303     ClearPreEditFlag();
304   }
305
306   void UpdateModel( OperationsMask operationsRequired );
307
308   /**
309    * @brief Retrieve the default fonts.
310    *
311    * @param[out] fonts The default font family, style and point sizes.
312    * @param[in] numberOfCharacters The number of characters in the logical model.
313    */
314   void GetDefaultFonts( Dali::Vector<FontRun>& fonts, Length numberOfCharacters );
315
316   void OnCursorKeyEvent( const Event& event );
317
318   void OnTapEvent( const Event& event );
319
320   void OnPanEvent( const Event& event );
321
322   void OnHandleEvent( const Event& event );
323
324   void RepositionSelectionHandles( float visualX, float visualY );
325
326   void ChangeState( EventData::State newState );
327
328   LineIndex GetClosestLine( float y ) const;
329
330   /**
331    * @brief Retrieves the cursor's logical position for a given touch point x,y
332    *
333    * @param[in] visualX The touch point x.
334    * @param[in] visualY The touch point y.
335    *
336    * @return The logical cursor position (in characters). 0 is just before the first character, a value equal to the number of characters is just after the last character.
337    */
338   CharacterIndex GetClosestCursorIndex( float visualX,
339                                         float visualY );
340
341   /**
342    * @brief Calculates the cursor's position for a given character index in the logical order.
343    *
344    * It retrieves as well the line's height and the cursor's height and
345    * if there is a valid alternative cursor, its position and height.
346    *
347    * @param[in] logical The logical cursor position (in characters). 0 is just before the first character, a value equal to the number of characters is just after the last character.
348    * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
349    */
350   void GetCursorPosition( CharacterIndex logical,
351                           CursorInfo& cursorInfo );
352
353   /**
354    * @brief Calculates the new cursor index.
355    *
356    * It takes into account that in some scripts multiple characters can form a glyph and all of them
357    * need to be jumped with one key event.
358    *
359    * @param[in] index The initial new index.
360    *
361    * @return The new cursor index.
362    */
363   CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
364
365   /**
366    * @brief Updates the cursor position.
367    *
368    * Retrieves the x,y position of the cursor logical position and sets it into the decorator.
369    * It sets the position of the secondary cursor if it's a valid one.
370    * Sets which cursors are active.
371    */
372   void UpdateCursorPosition();
373
374   /**
375    * @brief Updates the position of the given selection handle.
376    *
377    * @param[in] handleType One of the selection handles.
378    */
379   void UpdateSelectionHandle( HandleType handleType );
380
381   /**
382    * @biref Clamps the horizontal scrolling to get the control always filled with text.
383    *
384    * @param[in] actualSize The size of the laid out text.
385    */
386   void ClampHorizontalScroll( const Vector2& actualSize );
387
388   /**
389    * @biref Clamps the vertical scrolling to get the control always filled with text.
390    *
391    * @param[in] actualSize The size of the laid out text.
392    */
393   void ClampVerticalScroll( const Vector2& actualSize );
394
395   /**
396    * @brief Scrolls the text to make the cursor visible.
397    *
398    * This method is called after inserting text or moving the cursor with the keypad.
399    */
400   void ScrollToMakeCursorVisible();
401
402   /**
403    * @brief Scrolls the text to make the cursor visible.
404    *
405    * This method is called after deleting text.
406    */
407   void ScrollTextToMatchCursor();
408
409   ControlInterface& mControlInterface;     ///< Reference to the text controller.
410   LogicalModelPtr mLogicalModel;           ///< Pointer to the logical model.
411   VisualModelPtr  mVisualModel;            ///< Pointer to the visual model.
412   FontDefaults* mFontDefaults;             ///< Avoid allocating this when the user does not specify a font.
413   EventData* mEventData;                   ///< Avoid allocating everything for text input until EnableTextInput().
414   TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
415   View mView;                              ///< The view interface to the rendering back-end.
416   LayoutEngine mLayoutEngine;              ///< The layout engine.
417   std::vector<ModifyEvent> mModifyEvents;  ///< Temporary stores the text set until the next relayout.
418   Size mControlSize;                       ///< The size of the control.
419   Vector4 mTextColor;                      ///< The regular text color
420   Vector2 mAlignmentOffset;                ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
421   OperationsMask mOperationsPending;       ///< Operations pending to be done to layout the text.
422   Length mMaximumNumberOfCharacters;       ///< Maximum number of characters that can be inserted.
423   bool mRecalculateNaturalSize:1;          ///< Whether the natural size needs to be recalculated.
424 };
425
426 } // namespace Text
427
428 } // namespace Toolkit
429
430 } // namespace Dali
431
432 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__