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