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