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