[dali_1.0.40] Merge branch 'tizen'
[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':'TextLabel',                                      \
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     if(!mTitleActor)
245     {
246       mTitleActor = DemoHelper::CreateToolBarLabel( "" );
247       // Add title to the tool bar.
248       mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
249     }
250
251     mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
252   }
253
254   bool OnToolSelectLayout( Toolkit::Button button )
255   {
256     bool on = mItemView.IsVisible();
257
258     if( on )
259     {
260       LeaveSelection();
261     }
262     else
263     {
264       EnterSelection();
265     }
266
267     return true;
268   }
269
270   void LeaveSelection()
271   {
272
273   }
274
275   void EnterSelection()
276   {
277     Stage stage = Stage::GetCurrent();
278     stage.SetBackgroundColor( Color::WHITE );
279
280     mTapDetector = TapGestureDetector::New();
281     mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
282
283     if( mItemView )
284     {
285       stage.Remove( mItemView );
286     }
287
288     mFiles.clear();
289
290     mItemView = ItemView::New(*this);
291     stage.Add( mItemView );
292     mItemView.SetParentOrigin(ParentOrigin::CENTER);
293     mItemView.SetAnchorPoint(AnchorPoint::CENTER);
294     mGridLayout = GridLayout::New();
295     mGridLayout->SetNumberOfColumns(1);
296
297     mGridLayout->SetItemSizeFunction(SetItemSize);
298
299     mGridLayout->SetTopMargin(DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight);
300
301     mItemView.AddLayout(*mGridLayout);
302
303     Vector3 size(stage.GetSize());
304     mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
305     mItemView.SetKeyboardFocusable( true );
306
307     mFiles.clear();
308     FileList files;
309
310     if( USER_DIRECTORY.size() )
311     {
312       DirectoryFilesByType( USER_DIRECTORY, "json", files );
313     }
314     else
315     {
316       DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
317     }
318
319     std::sort(files.begin(), files.end());
320
321     ItemId itemId = 0;
322     for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
323     {
324       JsonParser parser = JsonParser::New();
325
326       std::string data( GetFileContents( *iter ) );
327
328       parser.Parse( data );
329
330       if( parser.ParseError() )
331       {
332         std::cout << "Parser Error:" << *iter << std::endl;
333         std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
334         exit(1);
335       }
336
337       if( parser.GetRoot() )
338       {
339         if( const TreeNode* node = parser.GetRoot()->Find("stage") )
340         {
341           // only those with a stage section
342           if( node->Size() )
343           {
344             mFiles.push_back( *iter );
345
346             mItemView.InsertItem( Item(itemId,
347                                        MenuItem( ShortName( *iter ) ) ),
348                                   0.5f );
349
350             itemId++;
351           }
352           else
353           {
354             std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
355           }
356         }
357         else
358         {
359           std::cout << "Ignored file (no stage section):" << *iter << std::endl;
360         }
361       }
362     }
363
364     // Display item view on the stage
365     stage.Add( mItemView );
366
367     mItemView.SetVisible( true );
368     mBuilderLayer.SetVisible( false );
369
370     SetTitle("Select");
371
372     // Itemview renderes the previous items unless its scrolled. Not sure why at the moment so we force a scroll
373     mItemView.ScrollToItem(0, 0);
374
375   }
376
377   void ExitSelection()
378   {
379     mTapDetector.Reset();
380
381     mItemView.SetVisible( false );
382     mBuilderLayer.SetVisible( true );
383
384     SetTitle("View");
385   }
386
387   void OnTap( Actor actor, const TapGesture& tap )
388   {
389     ItemId id = mItemView.GetItemId( actor );
390
391     LoadFromFileList( id );
392   }
393
394   Actor MenuItem(const std::string& text)
395   {
396     TextLabel label = TextLabel::New( ShortName( text ) );
397     label.SetProperty( Dali::Toolkit::Control::Property::STYLE_NAME, "builderlabel" );
398     label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
399
400     // Hook up tap detector
401     mTapDetector.Attach( label );
402
403     return label;
404   }
405
406   bool OnTimer()
407   {
408     if( mFileWatcher.FileHasChanged() )
409     {
410       LoadFromFile( mFileWatcher.GetFilename() );
411     }
412
413     return true;
414   }
415
416   void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
417   {
418     Stage stage = Stage::GetCurrent();
419
420     builder = Builder::New();
421     builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit );
422
423     Property::Map defaultDirs;
424     defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ]  = DALI_IMAGE_DIR;
425     defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ]  = DALI_MODEL_DIR;
426     defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
427
428     builder.AddConstants( defaultDirs );
429
430     // render tasks may have been setup last load so remove them
431     RenderTaskList taskList = stage.GetRenderTaskList();
432     if( taskList.GetTaskCount() > 1 )
433     {
434       typedef std::vector<RenderTask> Collection;
435       typedef Collection::iterator ColIter;
436       Collection tasks;
437
438       for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
439       {
440         tasks.push_back( taskList.GetTask(i) );
441       }
442
443       for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
444       {
445         taskList.RemoveTask(*iter);
446       }
447
448       RenderTask defaultTask = taskList.GetTask(0);
449       defaultTask.SetSourceActor( stage.GetRootLayer() );
450       defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
451     }
452
453     unsigned int numChildren = layer.GetChildCount();
454
455     for(unsigned int i=0; i<numChildren; ++i)
456     {
457       layer.Remove( layer.GetChildAt(0) );
458     }
459
460     std::string data(GetFileContents(filename));
461
462     try
463     {
464       builder.LoadFromString(data);
465     }
466     catch(...)
467     {
468       builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
469     }
470
471     builder.AddActors( layer );
472   }
473
474
475   void LoadFromFileList( size_t index )
476   {
477     if( index < mFiles.size())
478     {
479       const std::string& name = mFiles[index];
480       mFileWatcher.SetFilename( name );
481       LoadFromFile( name );
482     }
483   }
484
485   void LoadFromFile( const std::string& name )
486   {
487     ReloadJsonFile( name, mBuilder, mBuilderLayer );
488
489     // do this here as GetCurrentSize()
490     mBuilderLayer.SetParentOrigin(ParentOrigin::CENTER);
491     mBuilderLayer.SetAnchorPoint(AnchorPoint::CENTER);
492     Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
493     size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
494     mBuilderLayer.SetSize( size );
495
496     mBuilderLayer.LowerToBottom();
497     Stage::GetCurrent().GetRootLayer().RaiseToTop();
498
499     ExitSelection();
500   }
501
502   void Create(Application& app)
503   {
504     DemoHelper::RequestThemeChange();
505
506     Stage stage = Stage::GetCurrent();
507
508     Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
509
510     Layer contents = DemoHelper::CreateView( app,
511                                              mView,
512                                              mToolBar,
513                                              BACKGROUND_IMAGE,
514                                              TOOLBAR_IMAGE,
515                                              "" );
516
517     SetTitle("Builder");
518
519     mBuilderLayer = Layer::New();
520     stage.GetRootLayer().Add(mBuilderLayer);
521
522
523     // Create an edit mode button. (left of toolbar)
524     Toolkit::PushButton editButton = Toolkit::PushButton::New();
525     editButton.SetBackgroundImage( ResourceImage::New( EDIT_IMAGE ) );
526     editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
527     editButton.SetLeaveRequired( true );
528     mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING  );
529
530     EnterSelection();
531
532     mTimer = Timer::New( 500 ); // ms
533     mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
534     mTimer.Start();
535
536   } // Create(app)
537
538   virtual unsigned int GetNumberOfItems()
539   {
540     return mFiles.size();
541   }
542
543   virtual Actor NewItem(unsigned int itemId)
544   {
545     DALI_ASSERT_DEBUG( itemId < mFiles.size() );
546     return MenuItem( ShortName( mFiles[itemId] ) );
547   }
548
549   /**
550    * Main key event handler
551    */
552   void OnKeyEvent(const KeyEvent& event)
553   {
554     if(event.state == KeyEvent::Down)
555     {
556       if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
557       {
558         if ( mItemView.IsVisible() )
559         {
560           mApp.Quit();
561         }
562         else
563         {
564           EnterSelection();
565         }
566       }
567     }
568   }
569
570   /**
571    * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
572    */
573   void OnBuilderQuit()
574   {
575     if ( mItemView.IsVisible() )
576     {
577       mApp.Quit();
578     }
579     else
580     {
581       EnterSelection();
582     }
583   }
584
585 private:
586   Application& mApp;
587
588   GridLayoutPtr mGridLayout;
589   ItemView mItemView;
590
591   Toolkit::Control mView;
592   unsigned int mOrientation;
593
594   Toolkit::ToolBar mToolBar;
595   TextLabel mTitleActor;             ///< The Toolbar's Title.
596
597   Layer mBuilderLayer;
598
599   Toolkit::Popup mMenu;
600
601   TapGestureDetector mTapDetector;
602
603   // builder
604   Builder mBuilder;
605
606   FileList mFiles;
607
608   FileWatcher mFileWatcher;
609   Timer mTimer;
610
611
612 };
613
614 //------------------------------------------------------------------------------
615 //
616 //
617 //
618 //------------------------------------------------------------------------------
619 int main(int argc, char **argv)
620 {
621   if(argc > 2)
622   {
623     if(strcmp(argv[1], "-f") == 0)
624     {
625       USER_DIRECTORY = argv[2];
626     }
627   }
628
629   Application app = Application::New(&argc, &argv);
630
631   ExampleApp dali_app(app);
632
633   app.MainLoop();
634
635   return 0;
636 }