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