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