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 //------------------------------------------------------------------------------
23 #include <dali/dali.h>
24 #include <dali-toolkit/dali-toolkit.h>
25 #include <dali-toolkit/devel-api/builder/builder.h>
26 #include <dali-toolkit/devel-api/builder/tree-node.h>
27 #include <dali-toolkit/devel-api/builder/json-parser.h>
28 #include <dali-toolkit/devel-api/controls/popup/popup.h>
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" );
56 const char* EDIT_IMAGE_SELECTED( DALI_IMAGE_DIR "icon-change-selected.png" );
58 std::string USER_DIRECTORY;
60 std::string JSON_BROKEN(" \
67 'parentOrigin': 'CENTER', \
68 'text':'COULD NOT LOAD JSON FILE' \
74 std::string ReplaceQuotes(const std::string &single_quoted)
76 std::string s(single_quoted);
78 // wrong as no embedded quote but had regex link problems
79 std::replace(s.begin(), s.end(), '\'', '"');
84 std::string GetFileContents(const std::string &fn)
86 std::ifstream t(fn.c_str());
87 return std::string((std::istreambuf_iterator<char>(t)),
88 std::istreambuf_iterator<char>());
91 typedef std::vector<std::string> FileList;
93 void DirectoryFileList(const std::string& directory, FileList& files)
97 d = opendir(directory.c_str());
100 while ((dir = readdir(d)) != NULL)
102 if (dir->d_type == DT_REG)
104 files.push_back( directory + std::string(dir->d_name) );
112 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
114 typedef FileList Collection;
115 typedef FileList::iterator Iter;
118 DirectoryFileList(dir, allFiles);
120 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
122 size_t pos = (*iter).rfind( '.' );
123 if( pos != std::string::npos )
125 if( (*iter).substr( pos+1 ) == fileType )
127 files.push_back( (*iter) );
133 const std::string ShortName( const std::string& name )
135 size_t pos = name.rfind( '/' );
137 if( pos != std::string::npos )
139 return name.substr( pos );
147 //------------------------------------------------------------------------------
151 //------------------------------------------------------------------------------
157 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
159 void SetFilename(const std::string &fn);
160 std::string GetFilename() const;
162 bool FileHasChanged(void);
163 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
167 // FileWatcher(const FileWatcher&);
168 // FileWatcher &operator=(const FileWatcher &);
170 std::time_t mLastTime;
171 std::string mstringPath;
175 FileWatcher::FileWatcher(void) : mLastTime(0)
179 bool FileWatcher::FileHasChanged(void)
183 if(0 != stat(mstringPath.c_str(), &buf))
189 if(buf.st_mtime > mLastTime)
191 mLastTime = buf.st_mtime;
196 mLastTime = buf.st_mtime;
204 FileWatcher::~FileWatcher()
208 void FileWatcher::SetFilename(const std::string &fn)
211 FileHasChanged(); // update last time
214 std::string FileWatcher::GetFilename(void) const
223 //------------------------------------------------------------------------------
227 //------------------------------------------------------------------------------
228 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
231 ExampleApp(Application &app) : mApp(app)
233 app.InitSignal().Connect(this, &ExampleApp::Create);
240 void SetTitle(const std::string& title)
244 mTitleActor = DemoHelper::CreateToolBarLabel( "" );
245 // Add title to the tool bar.
246 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
249 mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
252 bool OnToolSelectLayout( Toolkit::Button button )
254 bool on = mItemView.IsVisible();
268 void LeaveSelection()
273 void EnterSelection()
275 Stage stage = Stage::GetCurrent();
276 stage.SetBackgroundColor( Color::WHITE );
278 mTapDetector = TapGestureDetector::New();
279 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
283 stage.Remove( mItemView );
288 mItemView = ItemView::New(*this);
289 stage.Add( mItemView );
290 mItemView.SetParentOrigin(ParentOrigin::CENTER);
291 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
292 mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
294 mLayout->SetItemSize( Vector3( stage.GetSize().width, 50, 1 ) );
296 mItemView.AddLayout( *mLayout );
298 mItemView.SetKeyboardFocusable( true );
303 if( USER_DIRECTORY.size() )
305 DirectoryFilesByType( USER_DIRECTORY, "json", files );
309 DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
312 std::sort(files.begin(), files.end());
315 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
317 JsonParser parser = JsonParser::New();
319 std::string data( GetFileContents( *iter ) );
321 parser.Parse( data );
323 if( parser.ParseError() )
325 std::cout << "Parser Error:" << *iter << std::endl;
326 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
330 if( parser.GetRoot() )
332 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
334 // only those with a stage section
337 mFiles.push_back( *iter );
339 mItemView.InsertItem( Item(itemId,
340 MenuItem( ShortName( *iter ) ) ),
347 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
352 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
357 // Display item view on the stage
358 stage.Add( mItemView );
360 mItemView.SetVisible( true );
361 mBuilderLayer.SetVisible( false );
365 // Activate the layout
366 Vector3 size(stage.GetSize());
367 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
372 mTapDetector.Reset();
374 mItemView.SetVisible( false );
375 mBuilderLayer.SetVisible( true );
380 void OnTap( Actor actor, const TapGesture& tap )
382 ItemId id = mItemView.GetItemId( actor );
384 LoadFromFileList( id );
387 Actor MenuItem(const std::string& text)
389 TextLabel label = TextLabel::New( ShortName( text ) );
390 label.SetProperty( Dali::Toolkit::Control::Property::STYLE_NAME, "builderlabel" );
391 label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
393 // Hook up tap detector
394 mTapDetector.Attach( label );
401 if( mFileWatcher.FileHasChanged() )
403 LoadFromFile( mFileWatcher.GetFilename() );
409 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
411 Stage stage = Stage::GetCurrent();
413 builder = Builder::New();
414 builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit );
416 Property::Map defaultDirs;
417 defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
418 defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;
419 defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
421 builder.AddConstants( defaultDirs );
423 // render tasks may have been setup last load so remove them
424 RenderTaskList taskList = stage.GetRenderTaskList();
425 if( taskList.GetTaskCount() > 1 )
427 typedef std::vector<RenderTask> Collection;
428 typedef Collection::iterator ColIter;
431 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
433 tasks.push_back( taskList.GetTask(i) );
436 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
438 taskList.RemoveTask(*iter);
441 RenderTask defaultTask = taskList.GetTask(0);
442 defaultTask.SetSourceActor( stage.GetRootLayer() );
443 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
446 unsigned int numChildren = layer.GetChildCount();
448 for(unsigned int i=0; i<numChildren; ++i)
450 layer.Remove( layer.GetChildAt(0) );
453 std::string data(GetFileContents(filename));
457 builder.LoadFromString(data);
461 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
464 builder.AddActors( layer );
468 void LoadFromFileList( size_t index )
470 if( index < mFiles.size())
472 const std::string& name = mFiles[index];
473 mFileWatcher.SetFilename( name );
474 LoadFromFile( name );
478 void LoadFromFile( const std::string& name )
480 ReloadJsonFile( name, mBuilder, mBuilderLayer );
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 );
489 mBuilderLayer.LowerToBottom();
490 Stage::GetCurrent().GetRootLayer().RaiseToTop();
495 void Create(Application& app)
497 Stage stage = Stage::GetCurrent();
499 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
501 Layer contents = DemoHelper::CreateView( app,
510 mBuilderLayer = Layer::New();
511 stage.GetRootLayer().Add(mBuilderLayer);
514 // Create an edit mode button. (left of toolbar)
515 Toolkit::PushButton editButton = Toolkit::PushButton::New();
516 editButton.SetUnselectedImage( EDIT_IMAGE );
517 editButton.SetSelectedImage( EDIT_IMAGE_SELECTED );
518 editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
519 editButton.SetLeaveRequired( true );
520 mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
524 mTimer = Timer::New( 500 ); // ms
525 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
530 virtual unsigned int GetNumberOfItems()
532 return mFiles.size();
535 virtual Actor NewItem(unsigned int itemId)
537 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
538 return MenuItem( ShortName( mFiles[itemId] ) );
542 * Main key event handler
544 void OnKeyEvent(const KeyEvent& event)
546 if(event.state == KeyEvent::Down)
548 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
550 if ( mItemView.IsVisible() )
563 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
567 if ( mItemView.IsVisible() )
580 ItemLayoutPtr mLayout;
583 Toolkit::Control mView;
584 unsigned int mOrientation;
586 Toolkit::ToolBar mToolBar;
587 TextLabel mTitleActor; ///< The Toolbar's Title.
591 Toolkit::Popup mMenu;
593 TapGestureDetector mTapDetector;
600 FileWatcher mFileWatcher;
606 //------------------------------------------------------------------------------
610 //------------------------------------------------------------------------------
611 int main(int argc, char **argv)
615 if(strcmp(argv[1], "-f") == 0)
617 USER_DIRECTORY = argv[2];
621 Application app = Application::New(&argc, &argv, DALI_DEMO_THEME_PATH);
623 ExampleApp dali_app(app);