8b5b18d372a933412ac4838c278d90bf88b1e6df
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / text-controls / text-field-impl.cpp
1 /*
2  * Copyright (c) 2021 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-controls/text-field-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/actors/actor-devel.h>
23 #include <dali/devel-api/adaptor-framework/key-devel.h>
24 #include <dali/devel-api/common/stage.h>
25 #include <dali/devel-api/object/property-helper-devel.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/adaptor-framework/key.h>
28 #include <dali/public-api/common/dali-common.h>
29 #include <dali/public-api/object/type-registry-helper.h>
30 #include <cstring>
31
32 // INTERNAL INCLUDES
33 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
34 #include <dali-toolkit/devel-api/controls/control-devel.h>
35 #include <dali-toolkit/devel-api/controls/text-controls/text-field-devel.h>
36 #include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
37 #include <dali-toolkit/devel-api/text/rendering-backend.h>
38 #include <dali-toolkit/internal/controls/text-controls/text-field-property-handler.h>
39 #include <dali-toolkit/internal/styling/style-manager-impl.h>
40 #include <dali-toolkit/internal/text/rendering/text-backend.h>
41 #include <dali-toolkit/internal/text/text-effects-style.h>
42 #include <dali-toolkit/internal/text/text-enumerations-impl.h>
43 #include <dali-toolkit/internal/text/text-font-style.h>
44 #include <dali-toolkit/internal/text/text-view.h>
45 #include <dali-toolkit/public-api/text/text-enumerations.h>
46 #include <dali-toolkit/public-api/visuals/color-visual-properties.h>
47 #include <dali-toolkit/public-api/visuals/visual-properties.h>
48 #include <dali/integration-api/adaptor-framework/adaptor.h>
49
50 using namespace Dali::Toolkit::Text;
51
52 #if defined(DEBUG_ENABLED)
53 Debug::Filter* gTextFieldLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS");
54 #endif
55
56 namespace Dali
57 {
58 namespace Toolkit
59 {
60 namespace Internal
61 {
62 namespace // unnamed namespace
63 {
64 const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND;
65 } // unnamed namespace
66
67 namespace
68 {
69 // Type registration
70 BaseHandle Create()
71 {
72   return Toolkit::TextField::New();
73 }
74
75 // clang-format off
76 // Setup properties, signals and actions using the type-registry.
77 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextField, Toolkit::Control, Create );
78
79 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "text",                             STRING,    TEXT                                )
80 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "placeholderText",                  STRING,    PLACEHOLDER_TEXT                    )
81 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "placeholderTextFocused",           STRING,    PLACEHOLDER_TEXT_FOCUSED            )
82 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "fontFamily",                       STRING,    FONT_FAMILY                         )
83 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "fontStyle",                        MAP,       FONT_STYLE                          )
84 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "pointSize",                        FLOAT,     POINT_SIZE                          )
85 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "maxLength",                        INTEGER,   MAX_LENGTH                          )
86 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "exceedPolicy",                     INTEGER,   EXCEED_POLICY                       )
87 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "horizontalAlignment",              STRING,    HORIZONTAL_ALIGNMENT                )
88 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "verticalAlignment",                STRING,    VERTICAL_ALIGNMENT                  )
89 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "textColor",                        VECTOR4,   TEXT_COLOR                          )
90 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "placeholderTextColor",             VECTOR4,   PLACEHOLDER_TEXT_COLOR              )
91 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "primaryCursorColor",               VECTOR4,   PRIMARY_CURSOR_COLOR                )
92 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "secondaryCursorColor",             VECTOR4,   SECONDARY_CURSOR_COLOR              )
93 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "enableCursorBlink",                BOOLEAN,   ENABLE_CURSOR_BLINK                 )
94 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "cursorBlinkInterval",              FLOAT,     CURSOR_BLINK_INTERVAL               )
95 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "cursorBlinkDuration",              FLOAT,     CURSOR_BLINK_DURATION               )
96 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "cursorWidth",                      INTEGER,   CURSOR_WIDTH                        )
97 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "grabHandleImage",                  STRING,    GRAB_HANDLE_IMAGE                   )
98 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "grabHandlePressedImage",           STRING,    GRAB_HANDLE_PRESSED_IMAGE           )
99 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "scrollThreshold",                  FLOAT,     SCROLL_THRESHOLD                    )
100 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "scrollSpeed",                      FLOAT,     SCROLL_SPEED                        )
101 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHandleImageLeft",         MAP,       SELECTION_HANDLE_IMAGE_LEFT         )
102 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHandleImageRight",        MAP,       SELECTION_HANDLE_IMAGE_RIGHT        )
103 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHandlePressedImageLeft",  MAP,       SELECTION_HANDLE_PRESSED_IMAGE_LEFT )
104 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHandlePressedImageRight", MAP,       SELECTION_HANDLE_PRESSED_IMAGE_RIGHT)
105 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHandleMarkerImageLeft",   MAP,       SELECTION_HANDLE_MARKER_IMAGE_LEFT  )
106 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHandleMarkerImageRight",  MAP,       SELECTION_HANDLE_MARKER_IMAGE_RIGHT )
107 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "selectionHighlightColor",          VECTOR4,   SELECTION_HIGHLIGHT_COLOR           )
108 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "decorationBoundingBox",            RECTANGLE, DECORATION_BOUNDING_BOX             )
109 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputMethodSettings",              MAP,       INPUT_METHOD_SETTINGS               )
110 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputColor",                       VECTOR4,   INPUT_COLOR                         )
111 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "enableMarkup",                     BOOLEAN,   ENABLE_MARKUP                       )
112 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputFontFamily",                  STRING,    INPUT_FONT_FAMILY                   )
113 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputFontStyle",                   MAP,       INPUT_FONT_STYLE                    )
114 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputPointSize",                   FLOAT,     INPUT_POINT_SIZE                    )
115 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "underline",                        MAP,       UNDERLINE                           )
116 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputUnderline",                   MAP,       INPUT_UNDERLINE                     )
117 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "shadow",                           MAP,       SHADOW                              )
118 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputShadow",                      MAP,       INPUT_SHADOW                        )
119 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "emboss",                           MAP,       EMBOSS                              )
120 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputEmboss",                      MAP,       INPUT_EMBOSS                        )
121 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "outline",                          MAP,       OUTLINE                             )
122 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "inputOutline",                     MAP,       INPUT_OUTLINE                       )
123 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "hiddenInputSettings",              MAP,       HIDDEN_INPUT_SETTINGS               )
124 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "pixelSize",                        FLOAT,     PIXEL_SIZE                          )
125 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "enableSelection",                  BOOLEAN,   ENABLE_SELECTION                    )
126 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "placeholder",                      MAP,       PLACEHOLDER                         )
127 DALI_PROPERTY_REGISTRATION(Toolkit,                 TextField, "ellipsis",                         BOOLEAN,   ELLIPSIS                            )
128 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "enableShiftSelection",             BOOLEAN,   ENABLE_SHIFT_SELECTION              )
129 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "enableGrabHandle",                 BOOLEAN,   ENABLE_GRAB_HANDLE                  )
130 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "matchSystemLanguageDirection",     BOOLEAN,   MATCH_SYSTEM_LANGUAGE_DIRECTION     )
131 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "enableGrabHandlePopup",            BOOLEAN,   ENABLE_GRAB_HANDLE_POPUP            )
132 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "textBackground",                   VECTOR4,   BACKGROUND                          )
133 DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextField, "selectedText",                     STRING,    SELECTED_TEXT                       )
134 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "renderingBackend",                 INTEGER,   RENDERING_BACKEND                   )
135 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "selectedTextStart",                INTEGER,   SELECTED_TEXT_START                 )
136 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "selectedTextEnd",                  INTEGER,   SELECTED_TEXT_END                   )
137 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "enableEditing",                    BOOLEAN,   ENABLE_EDITING                      )
138 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "fontSizeScale",                    FLOAT,     FONT_SIZE_SCALE                     )
139 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "primaryCursorPosition",            INTEGER,   PRIMARY_CURSOR_POSITION             )
140 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "grabHandleColor",                  VECTOR4,   GRAB_HANDLE_COLOR                   )
141 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "inputFilter",                      MAP,       INPUT_FILTER                        )
142 DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit,           TextField, "ellipsisPosition",                 INTEGER,   ELLIPSIS_POSITION                   )
143
144 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "textChanged",           SIGNAL_TEXT_CHANGED           )
145 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "maxLengthReached",      SIGNAL_MAX_LENGTH_REACHED     )
146 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "inputStyleChanged",     SIGNAL_INPUT_STYLE_CHANGED    )
147 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "anchorClicked",         SIGNAL_ANCHOR_CLICKED         )
148 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "inputFiltered",         SIGNAL_INPUT_FILTERED         )
149 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "cursorPositionChanged", SIGNAL_CURSOR_POSITION_CHANGED)
150 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "selectionChanged",      SIGNAL_SELECTION_CHANGED      )
151 DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "selectionCleared",      SIGNAL_SELECTION_CLEARED      )
152
153 DALI_TYPE_REGISTRATION_END()
154 // clang-format on
155
156 } // namespace
157
158 Toolkit::TextField TextField::New()
159 {
160   // Create the implementation, temporarily owned by this handle on stack
161   IntrusivePtr<TextField> impl = new TextField();
162
163   // Pass ownership to CustomActor handle
164   Toolkit::TextField handle(*impl);
165
166   // Second-phase init of the implementation
167   // This can only be done after the CustomActor connection has been made...
168   impl->Initialize();
169
170   return handle;
171 }
172
173 void TextField::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
174 {
175   Toolkit::TextField textField = Toolkit::TextField::DownCast(Dali::BaseHandle(object));
176
177   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField SetProperty\n");
178
179   if(textField)
180   {
181     PropertyHandler::SetProperty(textField, index, value);
182   }
183 }
184
185 Property::Value TextField::GetProperty(BaseObject* object, Property::Index index)
186 {
187   Property::Value value;
188
189   Toolkit::TextField textField = Toolkit::TextField::DownCast(Dali::BaseHandle(object));
190
191   if(textField)
192   {
193     value = PropertyHandler::GetProperty(textField, index);
194   }
195
196   return value;
197 }
198
199 void TextField::SelectWholeText()
200 {
201   if(mController && mController->IsShowingRealText())
202   {
203     mController->SelectWholeText();
204     SetKeyInputFocus();
205   }
206 }
207
208 void TextField::SelectNone()
209 {
210   if(mController && mController->IsShowingRealText())
211   {
212     mController->SelectNone();
213   }
214 }
215
216 void TextField::SelectText(const uint32_t start, const uint32_t end)
217 {
218   if(mController && mController->IsShowingRealText())
219   {
220     mController->SelectText(start, end);
221     SetKeyInputFocus();
222   }
223 }
224
225 string TextField::GetSelectedText() const
226 {
227   string selectedText = "";
228   if(mController && mController->IsShowingRealText())
229   {
230     selectedText = mController->GetSelectedText();
231   }
232   return selectedText;
233 }
234
235 void TextField::SetTextSelectionRange(const uint32_t* start, const uint32_t* end)
236 {
237   if(mController && mController->IsShowingRealText())
238   {
239     mController->SetTextSelectionRange(start, end);
240     SetKeyInputFocus();
241   }
242 }
243
244 Uint32Pair TextField::GetTextSelectionRange() const
245 {
246   Uint32Pair range;
247   if(mController && mController->IsShowingRealText())
248   {
249     range = mController->GetTextSelectionRange();
250   }
251   return range;
252 }
253
254 string TextField::CopyText()
255 {
256   string copiedText = "";
257   if(mController && mController->IsShowingRealText())
258   {
259     copiedText = mController->CopyText();
260   }
261   return copiedText;
262 }
263
264 string TextField::CutText()
265 {
266   string cutText = "";
267   if(mController && mController->IsShowingRealText())
268   {
269     cutText = mController->CutText();
270   }
271   return cutText;
272 }
273
274 void TextField::PasteText()
275 {
276   if(mController)
277   {
278     SetKeyInputFocus(); //Giving focus to the field that was passed to the PasteText in case the passed field (current field) doesn't have focus.
279     mController->PasteText();
280   }
281 }
282
283 InputMethodContext TextField::GetInputMethodContext()
284 {
285   return mInputMethodContext;
286 }
287
288 bool TextField::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
289 {
290   Dali::BaseHandle handle(object);
291
292   bool               connected(true);
293   Toolkit::TextField field = Toolkit::TextField::DownCast(handle);
294
295   if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED))
296   {
297     field.TextChangedSignal().Connect(tracker, functor);
298   }
299   else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED))
300   {
301     field.MaxLengthReachedSignal().Connect(tracker, functor);
302   }
303   else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED))
304   {
305     field.InputStyleChangedSignal().Connect(tracker, functor);
306   }
307   else if(0 == strcmp(signalName.c_str(), SIGNAL_ANCHOR_CLICKED))
308   {
309     if(field)
310     {
311       Internal::TextField& fieldImpl(GetImpl(field));
312       fieldImpl.AnchorClickedSignal().Connect(tracker, functor);
313     }
314   }
315   else if(0 == strcmp(signalName.c_str(), SIGNAL_CURSOR_POSITION_CHANGED))
316   {
317     if(field)
318     {
319       Internal::TextField& fieldImpl(GetImpl(field));
320       fieldImpl.CursorPositionChangedSignal().Connect(tracker, functor);
321     }
322   }
323   else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_FILTERED))
324   {
325     if(field)
326     {
327       Internal::TextField& fieldImpl(GetImpl(field));
328       fieldImpl.InputFilteredSignal().Connect(tracker, functor);
329     }
330   }
331   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_CHANGED))
332   {
333     if(field)
334     {
335       Internal::TextField& fieldImpl(GetImpl(field));
336       fieldImpl.SelectionChangedSignal().Connect(tracker, functor);
337     }
338   }
339   else if(0 == strcmp(signalName.c_str(), SIGNAL_SELECTION_CLEARED))
340   {
341     if(field)
342     {
343       Internal::TextField& fieldImpl(GetImpl(field));
344       fieldImpl.SelectionClearedSignal().Connect(tracker, functor);
345     }
346   }
347   else
348   {
349     // signalName does not match any signal
350     connected = false;
351   }
352
353   return connected;
354 }
355
356 Toolkit::TextField::TextChangedSignalType& TextField::TextChangedSignal()
357 {
358   return mTextChangedSignal;
359 }
360
361 Toolkit::TextField::MaxLengthReachedSignalType& TextField::MaxLengthReachedSignal()
362 {
363   return mMaxLengthReachedSignal;
364 }
365
366 Toolkit::TextField::InputStyleChangedSignalType& TextField::InputStyleChangedSignal()
367 {
368   return mInputStyleChangedSignal;
369 }
370
371 DevelTextField::AnchorClickedSignalType& TextField::AnchorClickedSignal()
372 {
373   return mAnchorClickedSignal;
374 }
375
376 DevelTextField::CursorPositionChangedSignalType& TextField::CursorPositionChangedSignal()
377 {
378   return mCursorPositionChangedSignal;
379 }
380
381 DevelTextField::InputFilteredSignalType& TextField::InputFilteredSignal()
382 {
383   return mInputFilteredSignal;
384 }
385
386 DevelTextField::SelectionChangedSignalType& TextField::SelectionChangedSignal()
387 {
388   return mSelectionChangedSignal;
389 }
390
391 DevelTextField::SelectionClearedSignalType& TextField::SelectionClearedSignal()
392 {
393   return mSelectionClearedSignal;
394 }
395
396 void TextField::OnInitialize()
397 {
398   Actor self = Self();
399
400   mController = Text::Controller::New(this, this, this, this);
401
402   // When using the vector-based rendering, the size of the GLyphs are different
403   TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH;
404   mController->SetGlyphType(glyphType);
405
406   mDecorator = Text::Decorator::New(*mController,
407                                     *mController);
408
409   mInputMethodContext = InputMethodContext::New(self);
410
411   mController->GetLayoutEngine().SetLayout(Layout::Engine::SINGLE_LINE_BOX);
412
413   // Enables the text input.
414   mController->EnableTextInput(mDecorator, mInputMethodContext);
415
416   // Enables the horizontal scrolling after the text input has been enabled.
417   mController->SetHorizontalScrollEnabled(true);
418
419   // Disables the vertical scrolling.
420   mController->SetVerticalScrollEnabled(false);
421
422   // Disable the smooth handle panning.
423   mController->SetSmoothHandlePanEnabled(false);
424
425   mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT);
426   mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT);
427
428   // Sets layoutDirection value
429   Dali::Stage                 stage           = Dali::Stage::GetCurrent();
430   Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
431   mController->SetLayoutDirection(layoutDirection);
432
433   self.LayoutDirectionChangedSignal().Connect(this, &TextField::OnLayoutDirectionChanged);
434
435   // Forward input events to controller
436   EnableGestureDetection(static_cast<GestureType::Value>(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS));
437   GetTapGestureDetector().SetMaximumTapsRequired(2);
438   GetTapGestureDetector().ReceiveAllTapEvents(true);
439
440   self.TouchedSignal().Connect(this, &TextField::OnTouched);
441
442   // Set BoundingBox to stage size if not already set.
443   Rect<int> boundingBox;
444   mDecorator->GetBoundingBox(boundingBox);
445
446   if(boundingBox.IsEmpty())
447   {
448     Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
449     mDecorator->SetBoundingBox(Rect<int>(0.0f, 0.0f, stageSize.width, stageSize.height));
450   }
451
452   // Flip vertically the 'left' selection handle
453   mDecorator->FlipHandleVertically(LEFT_SELECTION_HANDLE, true);
454
455   // Fill-parent area by default
456   self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
457   self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
458   self.OnSceneSignal().Connect(this, &TextField::OnSceneConnect);
459
460   //Enable highightability
461   self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
462
463   DevelControl::SetInputMethodContext(*this, mInputMethodContext);
464
465   if(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == mExceedPolicy)
466   {
467     EnableClipping();
468   }
469
470   DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
471     return std::unique_ptr<Dali::Accessibility::Accessible>(
472       new AccessibleImpl(actor, Dali::Accessibility::Role::ENTRY));
473   });
474 }
475
476 void TextField::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change)
477 {
478   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnStyleChange\n");
479
480   switch(change)
481   {
482     case StyleChange::DEFAULT_FONT_CHANGE:
483     {
484       DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnStyleChange DEFAULT_FONT_CHANGE\n");
485       const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily();
486       // Property system did not set the font so should update it.
487       mController->UpdateAfterFontChange(newFont);
488       RelayoutRequest();
489       break;
490     }
491
492     case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
493     {
494       GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner()));
495       RelayoutRequest();
496       break;
497     }
498     case StyleChange::THEME_CHANGE:
499     {
500       // Nothing to do, let control base class handle this
501       break;
502     }
503   }
504
505   // Up call to Control
506   Control::OnStyleChange(styleManager, change);
507 }
508
509 Vector3 TextField::GetNaturalSize()
510 {
511   Extents padding;
512   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
513
514   Vector3 naturalSize = mController->GetNaturalSize();
515   naturalSize.width += (padding.start + padding.end);
516   naturalSize.height += (padding.top + padding.bottom);
517
518   return naturalSize;
519 }
520
521 float TextField::GetHeightForWidth(float width)
522 {
523   Extents padding;
524   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
525   return mController->GetHeightForWidth(width) + padding.top + padding.bottom;
526 }
527
528 void TextField::ResizeActor(Actor& actor, const Vector2& size)
529 {
530   if(actor.GetProperty<Vector3>(Dali::Actor::Property::SIZE).GetVectorXY() != size)
531   {
532     actor.SetProperty(Actor::Property::SIZE, size);
533   }
534 }
535
536 void TextField::OnRelayout(const Vector2& size, RelayoutContainer& container)
537 {
538   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField OnRelayout\n");
539
540   Actor self = Self();
541
542   Extents padding;
543   padding = self.GetProperty<Extents>(Toolkit::Control::Property::PADDING);
544
545   Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom));
546
547   // Support Right-To-Left of padding
548   Dali::LayoutDirection::Type layoutDirection = mController->GetLayoutDirection(self);
549
550   if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
551   {
552     std::swap(padding.start, padding.end);
553   }
554
555   if(mStencil)
556   {
557     mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
558     ResizeActor(mStencil, contentSize);
559   }
560   if(mActiveLayer)
561   {
562     mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
563     ResizeActor(mActiveLayer, contentSize);
564   }
565
566   // If there is text changed, callback is called.
567   if(mTextChanged)
568   {
569     EmitTextChangedSignal();
570   }
571
572   const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection);
573
574   if((Text::Controller::NONE_UPDATED != updateTextType) ||
575      !mRenderer)
576   {
577     DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnRelayout %p Displaying new contents\n", mController.Get());
578
579     if(mDecorator &&
580        (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType)))
581     {
582       mDecorator->Relayout(contentSize);
583     }
584
585     if(!mRenderer)
586     {
587       mRenderer = Backend::Get().NewRenderer(mRenderingBackend);
588     }
589
590     RenderText(updateTextType);
591   }
592
593   if(mCursorPositionChanged)
594   {
595     EmitCursorPositionChangedSignal();
596   }
597
598   if(mSelectionChanged)
599   {
600     EmitSelectionChangedSignal();
601   }
602
603   if(mSelectionCleared)
604   {
605     EmitSelectionClearedSignal();
606   }
607
608   // The text-field emits signals when the input style changes. These changes of style are
609   // detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals
610   // can't be emitted during the size negotiation as the callbacks may update the UI.
611   // The text-field adds an idle callback to the adaptor to emit the signals after the size negotiation.
612   if(!mController->IsInputStyleChangedSignalsQueueEmpty())
613   {
614     if(Adaptor::IsAvailable())
615     {
616       Adaptor& adaptor = Adaptor::Get();
617
618       if(NULL == mIdleCallback)
619       {
620         // @note: The callback manager takes the ownership of the callback object.
621         mIdleCallback = MakeCallback(this, &TextField::OnIdleSignal);
622         adaptor.AddIdle(mIdleCallback, false);
623       }
624     }
625   }
626 }
627
628 Text::ControllerPtr TextField::GetTextController()
629 {
630   return mController;
631 }
632
633 void TextField::RenderText(Text::Controller::UpdateTextType updateTextType)
634 {
635   Actor renderableActor;
636
637   if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType))
638   {
639     if(mRenderer)
640     {
641       Dali::Toolkit::TextField handle = Dali::Toolkit::TextField(GetOwner());
642
643       renderableActor = mRenderer->Render(mController->GetView(),
644                                           handle,
645                                           Property::INVALID_INDEX, // Animatable property not supported
646                                           mAlignmentOffset,
647                                           DepthIndex::CONTENT);
648     }
649
650     if(renderableActor != mRenderableActor)
651     {
652       UnparentAndReset(mBackgroundActor);
653       UnparentAndReset(mRenderableActor);
654       mRenderableActor = renderableActor;
655
656       if(mRenderableActor)
657       {
658         mBackgroundActor = mController->CreateBackgroundActor();
659       }
660     }
661   }
662
663   if(mRenderableActor)
664   {
665     const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition();
666
667     float renderableActorPositionX, renderableActorPositionY;
668
669     if(mStencil)
670     {
671       renderableActorPositionX = scrollOffset.x + mAlignmentOffset;
672       renderableActorPositionY = scrollOffset.y;
673     }
674     else
675     {
676       Extents padding;
677       padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
678
679       // Support Right-To-Left of padding
680       Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
681       if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
682       {
683         std::swap(padding.start, padding.end);
684       }
685
686       renderableActorPositionX = scrollOffset.x + mAlignmentOffset + padding.start;
687       renderableActorPositionY = scrollOffset.y + padding.top;
688     }
689
690     mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(renderableActorPositionX, renderableActorPositionY));
691
692     // Make sure the actors are parented correctly with/without clipping
693     Actor self = mStencil ? mStencil : Self();
694
695     Actor highlightActor;
696
697     for(std::vector<Actor>::iterator it    = mClippingDecorationActors.begin(),
698                                      endIt = mClippingDecorationActors.end();
699         it != endIt;
700         ++it)
701     {
702       self.Add(*it);
703       it->LowerToBottom();
704
705       if(it->GetProperty<std::string>(Dali::Actor::Property::NAME) == "HighlightActor")
706       {
707         highlightActor = *it;
708       }
709     }
710     mClippingDecorationActors.clear();
711
712     self.Add(mRenderableActor);
713
714     if(mBackgroundActor)
715     {
716       if(mDecorator && mDecorator->IsHighlightVisible())
717       {
718         self.Add(mBackgroundActor);
719         mBackgroundActor.SetProperty(Actor::Property::POSITION, Vector2(renderableActorPositionX, renderableActorPositionY)); // In text field's coords.
720         mBackgroundActor.LowerBelow(highlightActor);
721       }
722       else
723       {
724         mRenderableActor.Add(mBackgroundActor);
725         mBackgroundActor.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f)); // In renderable actor's coords.
726         mBackgroundActor.LowerToBottom();
727       }
728     }
729   }
730 }
731
732 void TextField::OnKeyInputFocusGained()
733 {
734   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnKeyInputFocusGained %p\n", mController.Get());
735   if(mInputMethodContext && IsEditable())
736   {
737     // All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows).
738     mInputMethodContext.ApplyOptions(mInputMethodOptions);
739     mInputMethodContext.NotifyTextInputMultiLine(false);
740
741     mInputMethodContext.StatusChangedSignal().Connect(this, &TextField::KeyboardStatusChanged);
742
743     mInputMethodContext.EventReceivedSignal().Connect(this, &TextField::OnInputMethodContextEvent);
744
745     // Notify that the text editing start.
746     mInputMethodContext.Activate();
747
748     // When window gain lost focus, the inputMethodContext is deactivated. Thus when window gain focus again, the inputMethodContext must be activated.
749     mInputMethodContext.SetRestoreAfterFocusLost(true);
750   }
751   ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
752
753   if(notifier)
754   {
755     notifier.ContentSelectedSignal().Connect(this, &TextField::OnClipboardTextSelected);
756   }
757
758   mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event
759
760   EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last.
761 }
762
763 void TextField::OnKeyInputFocusLost()
764 {
765   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField:OnKeyInputFocusLost %p\n", mController.Get());
766   if(mInputMethodContext)
767   {
768     mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextField::KeyboardStatusChanged);
769     // The text editing is finished. Therefore the inputMethodContext don't have restore activation.
770     mInputMethodContext.SetRestoreAfterFocusLost(false);
771
772     // Notify that the text editing finish.
773     mInputMethodContext.Deactivate();
774
775     mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextField::OnInputMethodContextEvent);
776   }
777   ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
778
779   if(notifier)
780   {
781     notifier.ContentSelectedSignal().Disconnect(this, &TextField::OnClipboardTextSelected);
782   }
783
784   mController->KeyboardFocusLostEvent();
785
786   EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last.
787 }
788
789 bool TextField::OnAccessibilityActivated()
790 {
791   SetKeyInputFocus();
792   return true;
793 }
794
795 void TextField::OnTap(const TapGesture& gesture)
796 {
797   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnTap %p\n", mController.Get());
798   if(mInputMethodContext && IsEditable())
799   {
800     mInputMethodContext.Activate();
801   }
802   // Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures
803   Extents padding;
804   padding                   = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
805   const Vector2& localPoint = gesture.GetLocalPoint();
806   mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top);
807   mController->AnchorEvent(localPoint.x - padding.start, localPoint.y - padding.top);
808
809   SetKeyInputFocus();
810 }
811
812 void TextField::OnPan(const PanGesture& gesture)
813 {
814   mController->PanEvent(gesture.GetState(), gesture.GetDisplacement());
815 }
816
817 void TextField::OnLongPress(const LongPressGesture& gesture)
818 {
819   if(mInputMethodContext && IsEditable())
820   {
821     mInputMethodContext.Activate();
822   }
823   Extents padding;
824   padding                   = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
825   const Vector2& localPoint = gesture.GetLocalPoint();
826   mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top);
827
828   SetKeyInputFocus();
829 }
830
831 bool TextField::OnKeyEvent(const KeyEvent& event)
832 {
833   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode());
834
835   if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape())
836   {
837     // Make sure ClearKeyInputFocus when only key is up
838     if(event.GetState() == KeyEvent::UP)
839     {
840       ClearKeyInputFocus();
841     }
842
843     return true;
844   }
845   else if(Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode())
846   {
847     // Do nothing when enter is comming.
848     return false;
849   }
850
851   return mController->KeyEvent(event);
852 }
853
854 void TextField::RequestTextRelayout()
855 {
856   RelayoutRequest();
857 }
858
859 bool TextField::IsEditable() const
860 {
861   return mController->IsEditable();
862 }
863
864 void TextField::SetEditable(bool editable)
865 {
866   mController->SetEditable(editable);
867   if(mInputMethodContext && !editable)
868   {
869     mInputMethodContext.Deactivate();
870   }
871 }
872
873 void TextField::TextInserted(unsigned int position, unsigned int length, const std::string& content)
874 {
875   if(Accessibility::IsUp())
876   {
877     Control::Impl::GetAccessibilityObject(Self())->EmitTextInserted(position, length, content);
878   }
879 }
880
881 void TextField::TextDeleted(unsigned int position, unsigned int length, const std::string& content)
882 {
883   if(Accessibility::IsUp())
884   {
885     Control::Impl::GetAccessibilityObject(Self())->EmitTextDeleted(position, length, content);
886   }
887 }
888
889 void TextField::CursorPositionChanged(unsigned int oldPosition, unsigned int newPosition)
890 {
891   if(Accessibility::IsUp())
892   {
893     Control::Impl::GetAccessibilityObject(Self())->EmitTextCursorMoved(newPosition);
894   }
895
896   if((oldPosition != newPosition) && !mCursorPositionChanged)
897   {
898     mCursorPositionChanged = true;
899     mOldPosition           = oldPosition;
900   }
901 }
902
903 void TextField::TextChanged(bool immediate)
904 {
905   if(immediate) // Emits TextChangedSignal immediately
906   {
907     EmitTextChangedSignal();
908   }
909   else
910   {
911     mTextChanged = true;
912   }
913 }
914
915 void TextField::EmitTextChangedSignal()
916 {
917   Dali::Toolkit::TextField handle(GetOwner());
918   mTextChangedSignal.Emit(handle);
919   mTextChanged = false;
920 }
921
922 void TextField::MaxLengthReached()
923 {
924   Dali::Toolkit::TextField handle(GetOwner());
925   mMaxLengthReachedSignal.Emit(handle);
926 }
927
928 void TextField::InputStyleChanged(Text::InputStyle::Mask inputStyleMask)
929 {
930   Dali::Toolkit::TextField handle(GetOwner());
931
932   Toolkit::TextField::InputStyle::Mask fieldInputStyleMask = Toolkit::TextField::InputStyle::NONE;
933
934   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_COLOR))
935   {
936     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::COLOR);
937   }
938   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_FAMILY))
939   {
940     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_FAMILY);
941   }
942   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_POINT_SIZE))
943   {
944     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::POINT_SIZE);
945   }
946   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WEIGHT))
947   {
948     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE);
949   }
950   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WIDTH))
951   {
952     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE);
953   }
954   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_SLANT))
955   {
956     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE);
957   }
958   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_UNDERLINE))
959   {
960     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::UNDERLINE);
961   }
962   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_SHADOW))
963   {
964     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::SHADOW);
965   }
966   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_EMBOSS))
967   {
968     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::EMBOSS);
969   }
970   if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_OUTLINE))
971   {
972     fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::OUTLINE);
973   }
974
975   mInputStyleChangedSignal.Emit(handle, fieldInputStyleMask);
976 }
977
978 void TextField::AnchorClicked(const std::string& href)
979 {
980   Dali::Toolkit::TextField handle(GetOwner());
981   mAnchorClickedSignal.Emit(handle, href.c_str(), href.length());
982 }
983
984 void TextField::EmitCursorPositionChangedSignal()
985 {
986   Dali::Toolkit::TextField handle(GetOwner());
987   mCursorPositionChangedSignal.Emit(handle, mOldPosition);
988   mCursorPositionChanged = false;
989 }
990
991 void TextField::InputFiltered(Toolkit::InputFilter::Property::Type type)
992 {
993   Dali::Toolkit::TextField handle(GetOwner());
994   mInputFilteredSignal.Emit(handle, type);
995 }
996
997 void TextField::EmitSelectionChangedSignal()
998 {
999   Dali::Toolkit::TextField handle(GetOwner());
1000   mSelectionChangedSignal.Emit(handle, mOldSelectionStart, mOldSelectionEnd);
1001   mSelectionChanged = false;
1002 }
1003
1004 void TextField::EmitSelectionClearedSignal()
1005 {
1006   Dali::Toolkit::TextField handle(GetOwner());
1007   mSelectionClearedSignal.Emit(handle);
1008   mSelectionCleared = false;
1009 }
1010
1011 void TextField::SelectionChanged(uint32_t oldStart, uint32_t oldEnd, uint32_t newStart, uint32_t newEnd)
1012 {
1013   if(((oldStart != newStart) || (oldEnd != newEnd)) && !mSelectionChanged)
1014   {
1015     if(newStart == newEnd)
1016     {
1017       mSelectionCleared = true;
1018     }
1019
1020     mSelectionChanged  = true;
1021     mOldSelectionStart = oldStart;
1022     mOldSelectionEnd   = oldEnd;
1023
1024     if(mOldSelectionStart > mOldSelectionEnd)
1025     {
1026       //swap
1027       uint32_t temp      = mOldSelectionStart;
1028       mOldSelectionStart = mOldSelectionEnd;
1029       mOldSelectionEnd   = temp;
1030     }
1031   }
1032 }
1033
1034 void TextField::AddDecoration(Actor& actor, bool needsClipping)
1035 {
1036   if(actor)
1037   {
1038     if(needsClipping)
1039     {
1040       mClippingDecorationActors.push_back(actor);
1041     }
1042     else
1043     {
1044       actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
1045       actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
1046       Self().Add(actor);
1047       mActiveLayer = actor;
1048     }
1049   }
1050 }
1051
1052 void TextField::GetControlBackgroundColor(Vector4& color) const
1053 {
1054   Property::Value propValue = Self().GetProperty(Toolkit::Control::Property::BACKGROUND);
1055   Property::Map*  resultMap = propValue.GetMap();
1056
1057   Property::Value* colorValue = nullptr;
1058   if(resultMap && (colorValue = resultMap->Find(ColorVisual::Property::MIX_COLOR)))
1059   {
1060     colorValue->Get(color);
1061   }
1062 }
1063
1064 void TextField::OnSceneConnect(Dali::Actor actor)
1065 {
1066   if(mHasBeenStaged)
1067   {
1068     RenderText(static_cast<Text::Controller::UpdateTextType>(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED));
1069   }
1070   else
1071   {
1072     mHasBeenStaged = true;
1073   }
1074 }
1075
1076 InputMethodContext::CallbackData TextField::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent)
1077 {
1078   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName);
1079   return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent);
1080 }
1081
1082 void TextField::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType)
1083 {
1084   if(mDecorator)
1085   {
1086     Property::Map map;
1087     map[PropertyHandler::IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType);
1088
1089     value = map;
1090   }
1091 }
1092
1093 void TextField::EnableClipping()
1094 {
1095   if(!mStencil)
1096   {
1097     // Creates an extra control to be used as stencil buffer.
1098     mStencil = Control::New();
1099     mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
1100     mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
1101
1102     // Creates a background visual. Even if the color is transparent it updates the stencil.
1103     mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND,
1104                          Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT));
1105
1106     // Enable the clipping property.
1107     mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX);
1108     mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
1109
1110     Self().Add(mStencil);
1111   }
1112 }
1113
1114 void TextField::OnClipboardTextSelected(ClipboardEventNotifier& clipboard)
1115 {
1116   mController->PasteClipboardItemEvent();
1117 }
1118
1119 void TextField::KeyboardStatusChanged(bool keyboardShown)
1120 {
1121   DALI_LOG_INFO(gTextFieldLogFilter, Debug::Verbose, "TextField::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown);
1122
1123   // Just hide the grab handle when keyboard is hidden.
1124   if(!keyboardShown)
1125   {
1126     mController->KeyboardFocusLostEvent();
1127   }
1128   else
1129   {
1130     mController->KeyboardFocusGainEvent(); // Initially called by OnKeyInputFocusGained
1131   }
1132 }
1133
1134 void TextField::OnSceneConnection(int depth)
1135 {
1136   // Sets the depth to the visuals inside the text's decorator.
1137   mDecorator->SetTextDepth(depth);
1138
1139   // The depth of the text renderer is set in the RenderText() called from OnRelayout().
1140
1141   // Call the Control::OnSceneConnection() to set the depth of the background.
1142   Control::OnSceneConnection(depth);
1143 }
1144
1145 bool TextField::OnTouched(Actor actor, const TouchEvent& touch)
1146 {
1147   return false;
1148 }
1149
1150 void TextField::OnLayoutDirectionChanged(Actor actor, LayoutDirection::Type type)
1151 {
1152   mController->ChangedLayoutDirection();
1153 }
1154
1155 void TextField::OnIdleSignal()
1156 {
1157   // Emits the change of input style signals.
1158   mController->ProcessInputStyleChangedSignals();
1159
1160   // Set the pointer to null as the callback manager deletes the callback after execute it.
1161   mIdleCallback = NULL;
1162 }
1163
1164 TextField::TextField()
1165 : Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
1166   mIdleCallback(NULL),
1167   mAlignmentOffset(0.f),
1168   mRenderingBackend(DEFAULT_RENDERING_BACKEND),
1169   mExceedPolicy(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP),
1170   mHasBeenStaged(false),
1171   mTextChanged(false),
1172   mCursorPositionChanged(false),
1173   mSelectionChanged(false),
1174   mSelectionCleared(false),
1175   mOldPosition(0u),
1176   mOldSelectionStart(0u),
1177   mOldSelectionEnd(0u)
1178 {
1179 }
1180
1181 TextField::~TextField()
1182 {
1183   UnparentAndReset(mStencil);
1184
1185   if((NULL != mIdleCallback) && Adaptor::IsAvailable())
1186   {
1187     Adaptor::Get().RemoveIdle(mIdleCallback);
1188   }
1189 }
1190
1191 std::string TextField::AccessibleImpl::GetName()
1192 {
1193   auto self = Toolkit::TextField::DownCast(Self());
1194   return self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1195 }
1196
1197 std::string TextField::AccessibleImpl::GetText(size_t startOffset, size_t endOffset)
1198 {
1199   if(endOffset <= startOffset)
1200   {
1201     return {};
1202   }
1203
1204   auto self = Toolkit::TextField::DownCast(Self());
1205   auto text = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1206
1207   if(startOffset > text.size() || endOffset > text.size())
1208   {
1209     return {};
1210   }
1211
1212   return text.substr(startOffset, endOffset - startOffset);
1213 }
1214
1215 size_t TextField::AccessibleImpl::GetCharacterCount()
1216 {
1217   auto self = Toolkit::TextField::DownCast(Self());
1218   auto text = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1219
1220   return text.size();
1221 }
1222
1223 size_t TextField::AccessibleImpl::GetCursorOffset()
1224 {
1225   auto self = Toolkit::TextField::DownCast(Self());
1226   return Dali::Toolkit::GetImpl(self).GetTextController()->GetCursorPosition();
1227 }
1228
1229 bool TextField::AccessibleImpl::SetCursorOffset(size_t offset)
1230 {
1231   auto self = Toolkit::TextField::DownCast(Self());
1232   auto text = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1233   if(offset > text.size())
1234   {
1235     return false;
1236   }
1237
1238   auto& selfImpl = Dali::Toolkit::GetImpl(self);
1239   selfImpl.GetTextController()->ResetCursorPosition(offset);
1240   selfImpl.RequestTextRelayout();
1241
1242   return true;
1243 }
1244
1245 Dali::Accessibility::Range TextField::AccessibleImpl::GetTextAtOffset(
1246   size_t offset, Dali::Accessibility::TextBoundary boundary)
1247 {
1248   auto self     = Toolkit::TextField::DownCast(Self());
1249   auto text     = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1250   auto textSize = text.size();
1251
1252   auto range = Dali::Accessibility::Range{};
1253
1254   switch(boundary)
1255   {
1256     case Dali::Accessibility::TextBoundary::CHARACTER:
1257     {
1258       if(offset < textSize)
1259       {
1260         range.content     = text[offset];
1261         range.startOffset = offset;
1262         range.endOffset   = offset + 1;
1263       }
1264       break;
1265     }
1266     case Dali::Accessibility::TextBoundary::WORD:
1267     case Dali::Accessibility::TextBoundary::LINE:
1268     {
1269       auto textString = text.c_str();
1270       auto breaks     = std::vector<char>(textSize, 0);
1271
1272       if(boundary == Dali::Accessibility::TextBoundary::WORD)
1273       {
1274         Accessibility::Accessible::FindWordSeparationsUtf8(reinterpret_cast<const utf8_t*>(textString), textSize, "", breaks.data());
1275       }
1276       else
1277       {
1278         Accessibility::Accessible::FindLineSeparationsUtf8(reinterpret_cast<const utf8_t*>(textString), textSize, "", breaks.data());
1279       }
1280
1281       auto index   = 0u;
1282       auto counter = 0u;
1283       while(index < textSize && counter <= offset)
1284       {
1285         auto start = index;
1286         if(breaks[index])
1287         {
1288           while(breaks[index])
1289           {
1290             index++;
1291           }
1292           counter++;
1293         }
1294         else
1295         {
1296           if(boundary == Dali::Accessibility::TextBoundary::WORD)
1297           {
1298             index++;
1299           }
1300           if(boundary == Dali::Accessibility::TextBoundary::LINE)
1301           {
1302             counter++;
1303           }
1304         }
1305
1306         if((counter > 0) && ((counter - 1) == offset))
1307         {
1308           range.content     = text.substr(start, index - start + 1);
1309           range.startOffset = start;
1310           range.endOffset   = index + 1;
1311         }
1312
1313         if(boundary == Dali::Accessibility::TextBoundary::LINE)
1314         {
1315           index++;
1316         }
1317       }
1318       break;
1319     }
1320     case Dali::Accessibility::TextBoundary::SENTENCE:
1321     {
1322       /* not supported by default */
1323       break;
1324     }
1325     case Dali::Accessibility::TextBoundary::PARAGRAPH:
1326     {
1327       /* Paragraph is not supported by libunibreak library */
1328       break;
1329     }
1330     default:
1331       break;
1332   }
1333
1334   return range;
1335 }
1336
1337 Dali::Accessibility::Range TextField::AccessibleImpl::GetRangeOfSelection(size_t selectionIndex)
1338 {
1339   // Since DALi supports only one selection indexes higher than 0 are ignored
1340   if(selectionIndex > 0)
1341   {
1342     return {};
1343   }
1344
1345   auto        self       = Toolkit::TextField::DownCast(Self());
1346   auto        controller = Dali::Toolkit::GetImpl(self).GetTextController();
1347   std::string value{};
1348   controller->RetrieveSelection(value);
1349   auto indices = controller->GetSelectionIndexes();
1350
1351   return {static_cast<size_t>(indices.first), static_cast<size_t>(indices.second), value};
1352 }
1353
1354 bool TextField::AccessibleImpl::RemoveSelection(size_t selectionIndex)
1355 {
1356   // Since DALi supports only one selection indexes higher than 0 are ignored
1357   if(selectionIndex > 0)
1358   {
1359     return false;
1360   }
1361
1362   auto self = Toolkit::TextField::DownCast(Self());
1363   Dali::Toolkit::GetImpl(self).GetTextController()->SetSelection(0, 0);
1364   return true;
1365 }
1366
1367 bool TextField::AccessibleImpl::SetRangeOfSelection(size_t selectionIndex, size_t startOffset, size_t endOffset)
1368 {
1369   // Since DALi supports only one selection indexes higher than 0 are ignored
1370   if(selectionIndex > 0)
1371   {
1372     return false;
1373   }
1374
1375   auto self = Toolkit::TextField::DownCast(Self());
1376   Dali::Toolkit::GetImpl(self).GetTextController()->SetSelection(startOffset, endOffset);
1377   return true;
1378 }
1379
1380 bool TextField::AccessibleImpl::CopyText(size_t startPosition, size_t endPosition)
1381 {
1382   if(endPosition <= startPosition)
1383   {
1384     return false;
1385   }
1386
1387   auto self = Toolkit::TextField::DownCast(Self());
1388   auto text = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1389   Dali::Toolkit::GetImpl(self).GetTextController()->CopyStringToClipboard(text.substr(startPosition, endPosition - startPosition));
1390
1391   return true;
1392 }
1393
1394 bool TextField::AccessibleImpl::CutText(size_t startPosition, size_t endPosition)
1395 {
1396   if(endPosition <= startPosition)
1397   {
1398     return false;
1399   }
1400
1401   auto self = Toolkit::TextField::DownCast(Self());
1402   auto text = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1403   Dali::Toolkit::GetImpl(self).GetTextController()->CopyStringToClipboard(text.substr(startPosition, endPosition - startPosition));
1404
1405   self.SetProperty(Toolkit::TextField::Property::TEXT, text.substr(0, startPosition) + text.substr(endPosition));
1406
1407   return true;
1408 }
1409
1410 bool TextField::AccessibleImpl::DeleteText(size_t startPosition, size_t endPosition)
1411 {
1412   if(endPosition <= startPosition)
1413   {
1414     return false;
1415   }
1416
1417   auto self = Toolkit::TextField::DownCast(Self());
1418   auto text = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1419
1420   self.SetProperty(Toolkit::TextField::Property::TEXT, text.substr(0, startPosition) + text.substr(endPosition));
1421
1422   return true;
1423 }
1424
1425 Dali::Accessibility::States TextField::AccessibleImpl::CalculateStates()
1426 {
1427   using namespace Dali::Accessibility;
1428
1429   auto states = DevelControl::AccessibleImpl::CalculateStates();
1430
1431   states[State::EDITABLE]  = true;
1432   states[State::FOCUSABLE] = true;
1433
1434   Toolkit::Control focusControl = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl();
1435   if(mSelf == focusControl)
1436   {
1437     states[State::FOCUSED] = true;
1438   }
1439
1440   return states;
1441 }
1442
1443 bool TextField::AccessibleImpl::InsertText(size_t startPosition, std::string text)
1444 {
1445   auto self         = Toolkit::TextField::DownCast(Self());
1446   auto insertedText = self.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
1447
1448   insertedText.insert(startPosition, text);
1449
1450   self.SetProperty(Toolkit::TextField::Property::TEXT, std::move(insertedText));
1451
1452   return true;
1453 }
1454
1455 bool TextField::AccessibleImpl::SetTextContents(std::string newContents)
1456 {
1457   auto self = Toolkit::TextField::DownCast(Self());
1458   self.SetProperty(Toolkit::TextField::Property::TEXT, std::move(newContents));
1459   return true;
1460 }
1461
1462 } // namespace Internal
1463
1464 } // namespace Toolkit
1465
1466 } // namespace Dali