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