Updated demos to use DALi clang-format
[platform/core/uifw/dali-demo.git] / examples / text-editor / text-editor-example.cpp
1 /*
2  * Copyright (c) 2020 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 /**
19  * @file simple-text-editor-example.cpp
20  * @brief Very basic usage of TextEditor control
21  */
22
23 // EXTERNAL INCLUDES
24 #include <dali-toolkit/dali-toolkit.h>
25 #include <dali-toolkit/devel-api/controls/table-view/table-view.h>
26 #include <sstream>
27
28 // INTERNAL INCLUDES
29 #include "shared/view.h"
30
31 using namespace Dali;
32 using namespace Dali::Toolkit;
33
34 namespace
35 {
36 const char* const THEME_PATH(DEMO_STYLE_DIR "text-editor-example-theme.json"); ///< The theme used for this example
37 const Vector4     BACKGROUND_COLOR(0.04f, 0.345f, 0.392f, 1.0f);               ///< The background color.
38 const char*       TOOLBAR_IMAGE             = DEMO_IMAGE_DIR "top-bar.png";    ///< The tool-bar image.
39 const float       TOOLBAR_BUTTON_PERCENTAGE = 0.1f;                            ///< The button's space width as a percentage of the toolbar's width.
40 const float       TOOLBAR_TITLE_PERCENTAGE  = 0.7f;                            ///< The title's width as a percentage of the toolbar's width.
41 const float       TOOLBAR_HEIGHT_PERCENTAGE = 0.05f;                           ///< The toolbar's height as a percentage of the window's height.
42 const float       TOOLBAR_PADDING           = 4.f;                             ///< The padding in pixels.
43 const float       BUTTON_PERCENTAGE         = 0.8f;                            ///< The button's height as a percentage of the space for the buttons in the toolbar.
44 const Vector3     TEXT_EDITOR_RELATIVE_SIZE(0.9f, 0.5f, 1.0f);                 ///< The size of the text editor as a percentage of the window's size.
45 const Vector4     TEXT_EDITOR_BACKGROUND_COLOR(1.f, 1.f, 1.f, 0.15f);          ///< The background color of the text editor.
46
47 const Vector4      COLORS[]         = {Color::RED,
48                           Color::GREEN,
49                           Color::BLUE,
50                           Color::YELLOW,
51                           Color::CYAN,
52                           Color::MAGENTA,
53                           Color::WHITE,
54                           Color::BLACK};
55 const unsigned int NUMBER_OF_COLORS = sizeof(COLORS) / sizeof(Vector4);
56
57 } // Unnamed namespace
58
59 /**
60  * @brief The main class of the demo.
61  */
62 class TextEditorExample : public ConnectionTracker
63 {
64 public:
65   TextEditorExample(Application& application)
66   : mApplication(application)
67   {
68     // Connect to the Application's Init signal
69     mApplication.InitSignal().Connect(this, &TextEditorExample::Create);
70   }
71
72   ~TextEditorExample()
73   {
74     // Nothing to do here.
75   }
76
77   /**
78    * One-time setup in response to Application InitSignal.
79    */
80   void Create(Application& application)
81   {
82     Window window = application.GetWindow();
83
84     // Respond to key events
85     window.KeyEventSignal().Connect(this, &TextEditorExample::OnKeyEvent);
86
87     // Set a background color.
88     window.SetBackgroundColor(BACKGROUND_COLOR);
89
90     // The window size.
91     const Vector2 windowSize = window.GetSize();
92
93     // Creates a default view with a default tool bar.
94     // The view is added to the window.
95
96     // Set the toolbar style
97     const float                 toolBarHeight = TOOLBAR_HEIGHT_PERCENTAGE * windowSize.height;
98     const DemoHelper::ViewStyle viewStyle(TOOLBAR_BUTTON_PERCENTAGE,
99                                           TOOLBAR_TITLE_PERCENTAGE,
100                                           toolBarHeight,
101                                           TOOLBAR_PADDING);
102
103     Layer contents = DemoHelper::CreateView(mApplication,
104                                             mView,
105                                             mToolBar,
106                                             "",
107                                             TOOLBAR_IMAGE,
108                                             "",
109                                             viewStyle);
110
111     // Create a label for the color selection button.
112     // The button will be a child of this, so as to be placed next to it.
113     TextLabel colorLabel = TextLabel::New("Text Color: ");
114     colorLabel.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::WIDTH);
115     colorLabel.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
116     colorLabel.SetProperty(TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER");
117
118     // Create a container for the color button, to layout the drop-down list below it.
119     mColorContainer = Control::New();
120     mColorContainer.SetResizePolicy(ResizePolicy::DIMENSION_DEPENDENCY, Dimension::WIDTH);
121     mColorContainer.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::HEIGHT);
122     mColorContainer.SetProperty(Actor::Property::SIZE_MODE_FACTOR, Vector3(0.0f, BUTTON_PERCENTAGE, 0.0f));
123
124     // Place to right of parent.
125     mColorContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_RIGHT);
126     mColorContainer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT);
127     colorLabel.Add(mColorContainer);
128
129     // Add border to highlight harder-to-see colors.
130     // We use a color rather than border visual as the container will always be behind the button.
131     Property::Map colorMap;
132     colorMap.Insert(Toolkit::Visual::Property::TYPE, Visual::COLOR);
133     colorMap.Insert(ColorVisual::Property::MIX_COLOR, Color::BLACK);
134     mColorContainer.SetProperty(Control::Property::BACKGROUND, colorMap);
135
136     // Create a 'select color' button.
137     mColorButtonOption = Toolkit::PushButton::New();
138     mColorButtonOption.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
139     mColorButtonOption.SetProperty(Actor::Property::SIZE_MODE_FACTOR, Vector3(0.9f, 0.9f, 0.0f)); // Smaller than container to show border.
140     mColorButtonOption.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
141     mColorButtonOption.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
142
143     SetButtonColor(mColorButtonOption, Color::BLACK);
144
145     mColorButtonOption.ClickedSignal().Connect(this, &TextEditorExample::OnChangeColorButtonClicked);
146     mColorContainer.Add(mColorButtonOption);
147
148     //Add label to toolbar, which will also add the color button next to it.
149     mToolBar.AddControl(colorLabel, viewStyle.mToolBarButtonPercentage, Toolkit::Alignment::HORIZONTAL_LEFT, DemoHelper::DEFAULT_MODE_SWITCH_PADDING);
150
151     // Create the text editor.
152     mEditor = TextEditor::New();
153     mEditor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER);
154     mEditor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER);
155     mEditor.SetProperty(Actor::Property::POSITION, Vector3(0.f, toolBarHeight * 2.0f, 0.f));
156     mEditor.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
157     mEditor.SetProperty(Actor::Property::SIZE_MODE_FACTOR, TEXT_EDITOR_RELATIVE_SIZE);
158
159     mEditor.SetBackgroundColor(TEXT_EDITOR_BACKGROUND_COLOR);
160
161     const Size boundingBoxSize(windowSize * TEXT_EDITOR_RELATIVE_SIZE.GetVectorXY());
162     Rect<int>  boundingBox(0,
163                           static_cast<int>(toolBarHeight),
164                           static_cast<int>(boundingBoxSize.width),
165                           static_cast<int>(boundingBoxSize.height - toolBarHeight));
166
167     mEditor.SetProperty(TextEditor::Property::DECORATION_BOUNDING_BOX, boundingBox);
168     mEditor.SetProperty(TextEditor::Property::TEXT_COLOR, Color::BLACK);
169     mEditor.SetProperty(TextEditor::Property::TEXT,
170                         "Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n"
171                         "Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n"
172                         "Ne nec nulla regione albucius, mea doctus delenit ad!\n"
173                         "Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n"
174                         "Quidam corpora at duo. An eos possim scripserit?\n\n"
175                         "Aťqui dicant sěnťenťíae aň vel!\n"
176                         "Vis viris médiocrem elaboraret ét, verear civibus moderatius ex duo!\n"
177                         "Án veri laborě iňtěgré quó, mei aď poššit lobortis, mei prompťa čonsťitůťó eů.\n"
178                         "Aliquip sanctůs delicáta quí ěá, et natum aliquam est?\n"
179                         "Asšúm sapěret usu ůť.\n"
180                         "Síť ut apeirián laboramúš percipitur, sůas hařum ín éos?\n");
181
182     mEditor.InputStyleChangedSignal().Connect(this, &TextEditorExample::OnTextInputStyleChanged);
183
184     contents.Add(mEditor);
185     StyleManager styleManager = StyleManager::Get();
186     styleManager.ApplyTheme(THEME_PATH);
187   }
188
189   void CreateButtonContainer()
190   {
191     mButtonContainer = Toolkit::TableView::New(NUMBER_OF_COLORS, 1u);
192     mButtonContainer.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
193     mButtonContainer.SetProperty(Actor::Property::SIZE_MODE_FACTOR, Vector3(1.0f, NUMBER_OF_COLORS, 1.0f));
194
195     // Place below color selection button.
196     mButtonContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER);
197     mButtonContainer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER);
198     mButtonContainer.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 2.f * TOOLBAR_PADDING, 0.f));
199     mColorContainer.Add(mButtonContainer);
200
201     const Vector3 buttonPercentage(1.f, 0.8f / static_cast<float>(NUMBER_OF_COLORS), 1.f);
202     for(unsigned int index = 0u; index < NUMBER_OF_COLORS; ++index)
203     {
204       Toolkit::PushButton button = Toolkit::PushButton::New();
205       button.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
206       button.SetProperty(Actor::Property::SIZE_MODE_FACTOR, buttonPercentage);
207
208       std::ostringstream s;
209       s << "color" << index;
210       button.SetProperty(Dali::Actor::Property::NAME, s.str());
211
212       SetButtonColor(button, COLORS[index]);
213
214       button.ClickedSignal().Connect(this, &TextEditorExample::OnColorButtonClicked);
215
216       mButtonContainer.Add(button);
217     }
218   }
219
220   void OnKeyEvent(const KeyEvent& event)
221   {
222     if(event.GetState() == KeyEvent::DOWN)
223     {
224       if(IsKey(event, Dali::DALI_KEY_ESCAPE) || IsKey(event, Dali::DALI_KEY_BACK))
225       {
226         // Exit application when click back or escape.
227         mApplication.Quit();
228       }
229     }
230   }
231
232   bool OnChangeColorButtonClicked(Button button)
233   {
234     if(!mButtonContainer)
235     {
236       CreateButtonContainer();
237     }
238
239     mButtonContainer.SetProperty(Actor::Property::VISIBLE, true);
240     mButtonContainer.SetProperty(Actor::Property::SENSITIVE, true);
241     return true;
242   }
243
244   bool OnColorButtonClicked(Button button)
245   {
246     const std::string& name = button.GetProperty<std::string>(Dali::Actor::Property::NAME);
247
248     Vector4 color;
249     if("color" == name.substr(0u, 5u))
250     {
251       const unsigned int index = strtoul(name.substr(5u, 1u).c_str(), NULL, 10u);
252       color                    = COLORS[index];
253       mEditor.SetProperty(TextEditor::Property::INPUT_COLOR, color);
254     }
255
256     SetButtonColor(mColorButtonOption, color);
257
258     mButtonContainer.SetProperty(Actor::Property::VISIBLE, false);
259     mButtonContainer.SetProperty(Actor::Property::SENSITIVE, false);
260
261     return true;
262   }
263
264   void OnTextInputStyleChanged(TextEditor editor, TextEditor::InputStyle::Mask mask)
265   {
266     if(TextEditor::InputStyle::NONE != static_cast<TextEditor::InputStyle::Mask>(mask & TextEditor::InputStyle::COLOR))
267     {
268       const Vector4 color = editor.GetProperty(TextEditor::Property::INPUT_COLOR).Get<Vector4>();
269       SetButtonColor(mColorButtonOption, color);
270     }
271
272     editor.Reset();
273   }
274
275   void SetButtonColor(Button& button, const Vector4& color)
276   {
277     Property::Map colorVisualMap;
278     colorVisualMap.Add(Toolkit::Visual::Property::TYPE, Visual::COLOR)
279       .Add(ColorVisual::Property::MIX_COLOR, color);
280
281     button.SetProperty(Button::Property::UNSELECTED_BACKGROUND_VISUAL, colorVisualMap);
282     button.SetProperty(Button::Property::SELECTED_BACKGROUND_VISUAL, colorVisualMap);
283   }
284
285 private:
286   Application& mApplication;
287
288   Toolkit::Control    mView;
289   Toolkit::ToolBar    mToolBar;
290   Toolkit::TextEditor mEditor;
291   Toolkit::Control    mColorContainer;
292   Toolkit::PushButton mColorButtonOption;
293   Toolkit::TableView  mButtonContainer;
294 };
295
296 int DALI_EXPORT_API main(int argc, char** argv)
297 {
298   // DALI_DEMO_THEME_PATH not passed to Application so TextEditor example uses default Toolkit style sheet.
299   Application       application = Application::New(&argc, &argv);
300   TextEditorExample test(application);
301   application.MainLoop();
302   return 0;
303 }