Merge "Added an example that shows the FitKeepAspectRatio Fitting Mode with padding...
[platform/core/uifw/dali-demo.git] / examples / builder / examples.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 //
20 //
21 //------------------------------------------------------------------------------
22
23 #include <dali/dali.h>
24 #include <dali-toolkit/dali-toolkit.h>
25 #include <dali-toolkit/devel-api/builder/builder.h>
26 #include <dali-toolkit/devel-api/builder/tree-node.h>
27 #include <dali-toolkit/devel-api/builder/json-parser.h>
28 #include <dali-toolkit/devel-api/controls/buttons/button-devel.h>
29 #include <dali-toolkit/devel-api/controls/popup/popup.h>
30 #include <dali-toolkit/devel-api/controls/navigation-view/navigation-view.h>
31
32 #include <map>
33 #include <string>
34 #include <fstream>
35 #include <streambuf>
36 #include <sstream>
37 #include <dirent.h>
38 #include <stdio.h>
39 #include <iostream>
40
41 #include "sys/stat.h"
42 #include <ctime>
43 #include <cstring>
44
45 #include <dali/integration-api/debug.h>
46 #include <dali/devel-api/adaptor-framework/file-loader.h>
47 #include "shared/view.h"
48
49 #define TOKEN_STRING(x) #x
50
51 using namespace Dali;
52 using namespace Dali::Toolkit;
53
54 namespace
55 {
56
57 const char* BACKGROUND_IMAGE( "" );
58 const char* TOOLBAR_IMAGE( DEMO_IMAGE_DIR "top-bar.png" );
59 const char* EDIT_IMAGE( DEMO_IMAGE_DIR "icon-change.png" );
60 const char* EDIT_IMAGE_SELECTED( DEMO_IMAGE_DIR "icon-change-selected.png" );
61
62 std::string USER_DIRECTORY;
63
64 std::string JSON_BROKEN("                                      \
65 {                                                              \
66   'stage':                                                     \
67   [                                                            \
68     {                                                          \
69       'type':'TextLabel',                                      \
70       'size': [50,50,1],                                       \
71       'parentOrigin': 'CENTER',                                \
72       'text':'COULD NOT LOAD JSON FILE'                        \
73     }                                                          \
74   ]                                                            \
75 }                                                              \
76 ");
77
78 std::string ReplaceQuotes(const std::string &single_quoted)
79 {
80   std::string s(single_quoted);
81
82   // wrong as no embedded quote but had regex link problems
83   std::replace(s.begin(), s.end(), '\'', '"');
84
85   return s;
86 }
87
88 std::string GetFileContents(const std::string &fn)
89 {
90   std::streampos bufferSize = 0;
91   Dali::Vector<char> fileBuffer;
92   if( !Dali::FileLoader::ReadFile( fn, bufferSize, fileBuffer, FileLoader::FileType::BINARY ) )
93   {
94     return std::string();
95   }
96
97   return std::string( &fileBuffer[0], bufferSize );
98 };
99
100 typedef std::vector<std::string> FileList;
101
102 void DirectoryFileList(const std::string& directory, FileList& files)
103 {
104   DIR           *d;
105   struct dirent *dir;
106   d = opendir(directory.c_str());
107   if (d)
108   {
109     while ((dir = readdir(d)) != NULL)
110     {
111       if (dir->d_type == DT_REG)
112       {
113         files.push_back( directory + std::string(dir->d_name) );
114       }
115     }
116
117     closedir(d);
118   }
119 }
120
121 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
122 {
123   typedef FileList Collection;
124   typedef FileList::iterator Iter;
125
126   Collection allFiles;
127   DirectoryFileList(dir, allFiles);
128
129   for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
130   {
131     size_t pos = (*iter).rfind( '.' );
132     if( pos != std::string::npos )
133     {
134       if( (*iter).substr( pos+1 ) == fileType )
135       {
136         files.push_back( (*iter) );
137       }
138     }
139   }
140 }
141
142 const std::string ShortName( const std::string& name )
143 {
144   size_t pos = name.rfind( '/' );
145
146   if( pos != std::string::npos )
147   {
148     pos++;
149     return name.substr( pos );
150   }
151   else
152   {
153     return name;
154   }
155 }
156
157 //------------------------------------------------------------------------------
158 //
159 //
160 //
161 //------------------------------------------------------------------------------
162 class FileWatcher
163 {
164 public:
165   FileWatcher(void);
166   ~FileWatcher(void);
167   explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
168
169   void SetFilename(const std::string &fn);
170   std::string GetFilename() const;
171
172   bool FileHasChanged(void);
173   std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
174
175 private:
176   // compiler does
177   // FileWatcher(const FileWatcher&);
178   // FileWatcher &operator=(const FileWatcher &);
179
180   std::time_t mLastTime;
181   std::string mstringPath;
182
183 };
184
185 FileWatcher::FileWatcher(void) : mLastTime(0)
186 {
187 }
188
189 bool FileWatcher::FileHasChanged(void)
190 {
191   struct stat buf;
192
193   if(0 != stat(mstringPath.c_str(), &buf))
194   {
195     return false;
196   }
197   else
198   {
199     if(buf.st_mtime > mLastTime)
200     {
201       mLastTime = buf.st_mtime;
202       return true;
203     }
204     else
205     {
206       mLastTime = buf.st_mtime;
207       return false;
208     }
209   }
210
211   return false;
212 }
213
214 FileWatcher::~FileWatcher()
215 {
216 }
217
218 void FileWatcher::SetFilename(const std::string &fn)
219 {
220   mstringPath = fn;
221   FileHasChanged(); // update last time
222 }
223
224 std::string FileWatcher::GetFilename(void) const
225 {
226   return mstringPath;
227 }
228
229
230 } // anon namespace
231
232
233 //------------------------------------------------------------------------------
234 //
235 //
236 //
237 //------------------------------------------------------------------------------
238 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
239 {
240 public:
241   ExampleApp(Application &app) : mApp(app)
242   {
243     app.InitSignal().Connect(this, &ExampleApp::Create);
244   }
245
246   ~ExampleApp() {}
247
248 public:
249
250   void SetTitle(const std::string& title)
251   {
252     if(!mTitleActor)
253     {
254       mTitleActor = DemoHelper::CreateToolBarLabel( "" );
255       // Add title to the tool bar.
256       mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
257     }
258
259     mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
260   }
261
262   bool OnBackButtonPressed( Toolkit::Button button )
263   {
264     OnQuitOrBack();
265     return true;
266   }
267
268   void SetUpItemView()
269   {
270     Stage stage = Stage::GetCurrent();
271
272     mTapDetector = TapGestureDetector::New();
273     mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
274
275     mFiles.clear();
276
277     mItemView = ItemView::New(*this);
278
279     mItemView.SetParentOrigin(ParentOrigin::CENTER);
280     mItemView.SetAnchorPoint(AnchorPoint::CENTER);
281     mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
282
283     mLayout->SetItemSize( Vector3( stage.GetSize().width, 50, 1 ) );
284
285     mItemView.AddLayout( *mLayout );
286
287     mItemView.SetKeyboardFocusable( true );
288
289     mFiles.clear();
290     FileList files;
291
292     if( USER_DIRECTORY.size() )
293     {
294       DirectoryFilesByType( USER_DIRECTORY, "json", files );
295     }
296     else
297     {
298       DirectoryFilesByType( DEMO_SCRIPT_DIR, "json", files );
299     }
300
301     std::sort(files.begin(), files.end());
302
303     ItemId itemId = 0;
304     for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
305     {
306       JsonParser parser = JsonParser::New();
307
308       std::string data( GetFileContents( *iter ) );
309
310       parser.Parse( data );
311
312       if( parser.ParseError() )
313       {
314         std::cout << "Parser Error:" << *iter << std::endl;
315         std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
316         exit(1);
317       }
318
319       if( parser.GetRoot() )
320       {
321         if( const TreeNode* node = parser.GetRoot()->Find("stage") )
322         {
323           // only those with a stage section
324           if( node->Size() )
325           {
326             mFiles.push_back( *iter );
327
328             mItemView.InsertItem( Item(itemId,
329                                        MenuItem( ShortName( *iter ) ) ),
330                                   0.5f );
331
332             itemId++;
333           }
334           else
335           {
336             std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
337           }
338         }
339         else
340         {
341           std::cout << "Ignored file (no stage section):" << *iter << std::endl;
342         }
343       }
344     }
345
346     // Activate the layout
347     Vector3 size(stage.GetSize());
348     mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
349   }
350
351
352   void OnTap( Actor actor, const TapGesture& tap )
353   {
354     ItemId id = mItemView.GetItemId( actor );
355
356     LoadFromFileList( id );
357   }
358
359   Actor MenuItem(const std::string& text)
360   {
361     TextLabel label = TextLabel::New( ShortName( text ) );
362     label.SetStyleName( "BuilderLabel" );
363     label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
364
365     // Hook up tap detector
366     mTapDetector.Attach( label );
367
368     return label;
369   }
370
371   bool OnTimer()
372   {
373     if( mFileWatcher.FileHasChanged() )
374     {
375       LoadFromFile( mFileWatcher.GetFilename() );
376     }
377
378     return true;
379   }
380
381   void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
382   {
383     Stage stage = Stage::GetCurrent();
384
385     builder = Builder::New();
386     builder.QuitSignal().Connect( this, &ExampleApp::OnQuitOrBack );
387
388     Property::Map defaultDirs;
389     defaultDirs[ TOKEN_STRING(DEMO_IMAGE_DIR) ]  = DEMO_IMAGE_DIR;
390     defaultDirs[ TOKEN_STRING(DEMO_MODEL_DIR) ]  = DEMO_MODEL_DIR;
391     defaultDirs[ TOKEN_STRING(DEMO_SCRIPT_DIR) ] = DEMO_SCRIPT_DIR;
392
393     builder.AddConstants( defaultDirs );
394
395     // render tasks may have been setup last load so remove them
396     RenderTaskList taskList = stage.GetRenderTaskList();
397     if( taskList.GetTaskCount() > 1 )
398     {
399       typedef std::vector<RenderTask> Collection;
400       typedef Collection::iterator ColIter;
401       Collection tasks;
402
403       for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
404       {
405         tasks.push_back( taskList.GetTask(i) );
406       }
407
408       for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
409       {
410         taskList.RemoveTask(*iter);
411       }
412
413       RenderTask defaultTask = taskList.GetTask(0);
414       defaultTask.SetSourceActor( stage.GetRootLayer() );
415       defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
416     }
417
418     unsigned int numChildren = layer.GetChildCount();
419
420     for(unsigned int i=0; i<numChildren; ++i)
421     {
422       layer.Remove( layer.GetChildAt(0) );
423     }
424
425     std::string data(GetFileContents(filename));
426
427     try
428     {
429       builder.LoadFromString(data);
430     }
431     catch(...)
432     {
433       builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
434     }
435
436     builder.AddActors( layer );
437   }
438
439
440   void LoadFromFileList( size_t index )
441   {
442     if( index < mFiles.size())
443     {
444       const std::string& name = mFiles[index];
445       mFileWatcher.SetFilename( name );
446       LoadFromFile( name );
447     }
448   }
449
450   void LoadFromFile( const std::string& name )
451   {
452     ReloadJsonFile( name, mBuilder, mBuilderLayer );
453
454     mBuilderLayer.SetParentOrigin(ParentOrigin::BOTTOM_CENTER);
455     mBuilderLayer.SetAnchorPoint(AnchorPoint::BOTTOM_CENTER);
456     Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
457     size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
458     mBuilderLayer.SetSize( size );
459
460     mNavigationView.Push( mBuilderLayer );
461   }
462
463   void Create(Application& app)
464   {
465     Stage stage = Stage::GetCurrent();
466
467     Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
468
469     Layer contents = DemoHelper::CreateView( app,
470                                              mView,
471                                              mToolBar,
472                                              BACKGROUND_IMAGE,
473                                              TOOLBAR_IMAGE,
474                                              "" );
475
476     SetTitle("Select Example");
477
478     mBuilderLayer = Layer::New();
479
480     // Create an edit mode button. (left of toolbar)
481     Toolkit::PushButton backButton = Toolkit::PushButton::New();
482     backButton.SetProperty( Toolkit::DevelButton::Property::UNSELECTED_BACKGROUND_VISUAL, EDIT_IMAGE );
483     backButton.SetProperty( Toolkit::DevelButton::Property::SELECTED_BACKGROUND_VISUAL, EDIT_IMAGE_SELECTED );
484     backButton.ClickedSignal().Connect( this, &ExampleApp::OnBackButtonPressed);
485     backButton.SetLeaveRequired( true );
486     mToolBar.AddControl( backButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING  );
487
488     mNavigationView = Toolkit::NavigationView::New();
489     mNavigationView.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
490     mNavigationView.SetAnchorPoint( AnchorPoint::TOP_LEFT);
491
492     stage.Add( mNavigationView );
493
494     // Set up the background gradient.
495     Property::Array stopOffsets;
496     stopOffsets.PushBack( 0.0f );
497     stopOffsets.PushBack( 1.0f );
498     Property::Array stopColors;
499     stopColors.PushBack( Color::WHITE );
500     stopColors.PushBack( Vector4( 0.45f, 0.70f, 0.80f, 1.0f ) ); // Medium bright, pastel blue
501     const float percentageStageHeight = stage.GetSize().height * 0.6f;
502
503     mNavigationView.SetProperty( Toolkit::Control::Property::BACKGROUND, Dali::Property::Map()
504       .Add( Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT )
505       .Add( Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets )
506       .Add( Toolkit::GradientVisual::Property::STOP_COLOR, stopColors )
507       .Add( Toolkit::GradientVisual::Property::START_POSITION, Vector2( 0.0f, -percentageStageHeight ) )
508       .Add( Toolkit::GradientVisual::Property::END_POSITION, Vector2( 0.0f, percentageStageHeight ) )
509       .Add( Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE ) );
510
511     SetUpItemView();
512     mNavigationView.Push( mItemView );
513
514     mTimer = Timer::New( 500 ); // ms
515     mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
516     mTimer.Start();
517
518   } // Create(app)
519
520   virtual unsigned int GetNumberOfItems()
521   {
522     return mFiles.size();
523   }
524
525   virtual Actor NewItem(unsigned int itemId)
526   {
527     DALI_ASSERT_DEBUG( itemId < mFiles.size() );
528     return MenuItem( ShortName( mFiles[itemId] ) );
529   }
530
531   /**
532    * Main key event handler
533    */
534   void OnKeyEvent(const KeyEvent& event)
535   {
536     if(event.state == KeyEvent::Down)
537     {
538       if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
539       {
540         OnQuitOrBack();
541       }
542     }
543   }
544
545   /**
546    * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
547    */
548   void OnQuitOrBack()
549   {
550     if ( mItemView.OnStage() )
551     {
552       mApp.Quit();
553     }
554     else
555     {
556       mNavigationView.Pop();
557     }
558   }
559
560 private:
561   Application& mApp;
562
563   ItemLayoutPtr mLayout;
564   ItemView mItemView;
565   Toolkit::NavigationView mNavigationView;
566
567   Toolkit::Control mView;
568
569   Toolkit::ToolBar mToolBar;
570   TextLabel mTitleActor;
571
572   Layer mBuilderLayer;
573
574   TapGestureDetector mTapDetector;
575
576   // builder
577   Builder mBuilder;
578
579   FileList mFiles;
580
581   FileWatcher mFileWatcher;
582   Timer mTimer;
583 };
584
585 //------------------------------------------------------------------------------
586 //
587 //
588 //
589 //------------------------------------------------------------------------------
590 int DALI_EXPORT_API main(int argc, char **argv)
591 {
592   if(argc > 2)
593   {
594     if(strcmp(argv[1], "-f") == 0)
595     {
596       USER_DIRECTORY = argv[2];
597     }
598   }
599
600   Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
601
602   ExampleApp dali_app(app);
603
604   app.MainLoop();
605
606   return 0;
607 }