2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 //------------------------------------------------------------------------------
21 //------------------------------------------------------------------------------
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>
33 #include <boost/scoped_ptr.hpp>
38 //#include <boost/regex.hpp>
42 #include <dali/integration-api/debug.h>
43 #include "../shared/view.h"
45 #define TOKEN_STRING(x) #x
48 using namespace Dali::Toolkit;
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" );
57 std::string USER_DIRECTORY;
59 std::string JSON_BROKEN(" \
66 'parent-origin': 'CENTER', \
67 'text':'COULD NOT LOAD JSON FILE' \
73 std::string ReplaceQuotes(const std::string &single_quoted)
75 std::string s(single_quoted);
77 // wrong as no embedded quote but had regex link problems
78 std::replace(s.begin(), s.end(), '\'', '"');
83 std::string GetFileContents(const std::string &fn)
85 std::ifstream t(fn.c_str());
86 return std::string((std::istreambuf_iterator<char>(t)),
87 std::istreambuf_iterator<char>());
90 typedef std::vector<std::string> FileList;
92 void DirectoryFileList(const std::string& directory, FileList& files)
96 d = opendir(directory.c_str());
99 while ((dir = readdir(d)) != NULL)
101 if (dir->d_type == DT_REG)
103 files.push_back( directory + std::string(dir->d_name) );
111 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
113 typedef FileList Collection;
114 typedef FileList::iterator Iter;
117 DirectoryFileList(dir, allFiles);
119 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
121 size_t pos = (*iter).rfind( '.' );
122 if( pos != std::string::npos )
124 if( (*iter).substr( pos+1 ) == fileType )
126 files.push_back( (*iter) );
132 const std::string ShortName( const std::string& name )
134 size_t pos = name.rfind( '/' );
136 if( pos != std::string::npos )
138 return name.substr( pos );
146 static Vector3 SetItemSize(unsigned int numberOfColumns, float layoutWidth, float sideMargin, float columnSpacing)
148 return Vector3(layoutWidth, 50, 1);
151 //------------------------------------------------------------------------------
155 //------------------------------------------------------------------------------
161 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
163 void SetFilename(const std::string &fn);
164 std::string GetFilename() const;
166 bool FileHasChanged(void);
167 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
171 // FileWatcher(const FileWatcher&);
172 // FileWatcher &operator=(const FileWatcher &);
174 std::time_t mLastTime;
175 std::string mstringPath;
179 FileWatcher::FileWatcher(void) : mLastTime(0)
183 bool FileWatcher::FileHasChanged(void)
187 if(0 != stat(mstringPath.c_str(), &buf))
193 if(buf.st_mtime > mLastTime)
195 mLastTime = buf.st_mtime;
200 mLastTime = buf.st_mtime;
208 FileWatcher::~FileWatcher()
212 void FileWatcher::SetFilename(const std::string &fn)
215 FileHasChanged(); // update last time
218 std::string FileWatcher::GetFilename(void) const
227 //------------------------------------------------------------------------------
231 //------------------------------------------------------------------------------
232 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
235 ExampleApp(Application &app) : mApp(app)
237 app.InitSignal().Connect(this, &ExampleApp::Create);
244 void SetTitle(const std::string& title)
249 bool OnToolSelectLayout( Toolkit::Button button )
251 bool on = mItemView.IsVisible();
265 void LeaveSelection()
270 void EnterSelection()
272 Stage stage = Stage::GetCurrent();
274 mTapDetector = TapGestureDetector::New();
275 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
279 stage.Remove( mItemView );
284 mItemView = ItemView::New(*this);
285 stage.Add( mItemView );
286 mItemView.SetParentOrigin(ParentOrigin::CENTER);
287 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
288 mGridLayout = GridLayout::New();
289 mGridLayout->SetNumberOfColumns(1);
291 mGridLayout->SetItemSizeFunction(SetItemSize);
293 mGridLayout->SetTopMargin(DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight);
295 mItemView.AddLayout(*mGridLayout);
297 Vector3 size(stage.GetSize());
298 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
299 mItemView.SetKeyboardFocusable( true );
304 if( USER_DIRECTORY.size() )
306 DirectoryFilesByType( USER_DIRECTORY, "json", files );
310 DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
313 std::sort(files.begin(), files.end());
316 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
318 JsonParser parser = JsonParser::New();
320 std::string data( GetFileContents( *iter ) );
322 parser.Parse( data );
324 if( parser.ParseError() )
326 std::cout << "Parser Error:" << *iter << std::endl;
327 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
331 if( parser.GetRoot() )
333 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
335 // only those with a stage section
338 mFiles.push_back( *iter );
340 mItemView.InsertItem( Item(itemId,
341 MenuItem( ShortName( *iter ) ) ),
348 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
353 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
358 // Display item view on the stage
359 stage.Add( mItemView );
361 mItemView.SetVisible( true );
362 mBuilderLayer.SetVisible( false );
366 // Itemview renderes the previous items unless its scrolled. Not sure why at the moment so we force a scroll
367 mItemView.ScrollToItem(0, 0);
373 mTapDetector.Reset();
375 mItemView.SetVisible( false );
376 mBuilderLayer.SetVisible( true );
381 void OnTap( Actor actor, const TapGesture& tap )
383 ItemId id = mItemView.GetItemId( actor );
385 LoadFromFileList( id );
388 Actor MenuItem(const std::string& text)
395 if( mFileWatcher.FileHasChanged() )
397 LoadFromFile( mFileWatcher.GetFilename() );
403 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
405 Stage stage = Stage::GetCurrent();
407 builder = Builder::New();
408 builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit );
410 Property::Map defaultDirs;
411 defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
412 defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;
413 defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
415 builder.AddConstants( defaultDirs );
417 // render tasks may have been setup last load so remove them
418 RenderTaskList taskList = stage.GetRenderTaskList();
419 if( taskList.GetTaskCount() > 1 )
421 typedef std::vector<RenderTask> Collection;
422 typedef Collection::iterator ColIter;
425 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
427 tasks.push_back( taskList.GetTask(i) );
430 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
432 taskList.RemoveTask(*iter);
435 RenderTask defaultTask = taskList.GetTask(0);
436 defaultTask.SetSourceActor( stage.GetRootLayer() );
437 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
440 unsigned int numChildren = layer.GetChildCount();
442 for(unsigned int i=0; i<numChildren; ++i)
444 layer.Remove( layer.GetChildAt(0) );
447 std::string data(GetFileContents(filename));
451 builder.LoadFromString(data);
455 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
458 builder.AddActors( layer );
463 void LoadFromFileList( size_t index )
465 if( index < mFiles.size())
467 const std::string& name = mFiles[index];
468 mFileWatcher.SetFilename( name );
469 LoadFromFile( name );
473 void LoadFromFile( const std::string& name )
475 ReloadJsonFile( name, mBuilder, mBuilderLayer );
477 // do this here as GetCurrentSize()
478 mBuilderLayer.SetParentOrigin(ParentOrigin::CENTER);
479 mBuilderLayer.SetAnchorPoint(AnchorPoint::CENTER);
480 Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
481 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
482 mBuilderLayer.SetSize( size );
484 mBuilderLayer.LowerToBottom();
485 Stage::GetCurrent().GetRootLayer().RaiseToTop();
490 void Create(Application& app)
492 Stage stage = Stage::GetCurrent();
494 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
496 Layer contents = DemoHelper::CreateView( app,
505 mBuilderLayer = Layer::New();
506 stage.GetRootLayer().Add(mBuilderLayer);
509 // Create an edit mode button. (left of toolbar)
510 Toolkit::PushButton editButton = Toolkit::PushButton::New();
511 editButton.SetBackgroundImage( ResourceImage::New( EDIT_IMAGE ) );
512 editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
513 editButton.SetLeaveRequired( true );
514 mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
518 mTimer = Timer::New( 500 ); // ms
519 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
524 virtual unsigned int GetNumberOfItems()
526 return mFiles.size();
529 virtual Actor NewItem(unsigned int itemId)
531 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
532 return MenuItem( ShortName( mFiles[itemId] ) );
536 * Main key event handler
538 void OnKeyEvent(const KeyEvent& event)
540 if(event.state == KeyEvent::Down)
542 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
544 if ( mItemView.IsVisible() )
557 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
561 if ( mItemView.IsVisible() )
574 GridLayoutPtr mGridLayout;
578 unsigned int mOrientation;
580 Toolkit::ToolBar mToolBar;
584 Toolkit::Popup mMenu;
586 TapGestureDetector mTapDetector;
593 FileWatcher mFileWatcher;
599 //------------------------------------------------------------------------------
603 //------------------------------------------------------------------------------
604 int main(int argc, char **argv)
608 if(strcmp(argv[1], "-f") == 0)
610 USER_DIRECTORY = argv[2];
614 Application app = Application::New(&argc, &argv);
616 ExampleApp dali_app(app);