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