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