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