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