2 * Copyright (c) 2017 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/buttons/button-devel.h>
29 #include <dali-toolkit/devel-api/controls/popup/popup.h>
30 #include <dali-toolkit/devel-api/controls/navigation-view/navigation-view.h>
45 #include <dali/integration-api/debug.h>
46 #include "shared/view.h"
48 #define TOKEN_STRING(x) #x
51 using namespace Dali::Toolkit;
56 const char* BACKGROUND_IMAGE( "" );
57 const char* TOOLBAR_IMAGE( DEMO_IMAGE_DIR "top-bar.png" );
58 const char* EDIT_IMAGE( DEMO_IMAGE_DIR "icon-change.png" );
59 const char* EDIT_IMAGE_SELECTED( DEMO_IMAGE_DIR "icon-change-selected.png" );
61 std::string USER_DIRECTORY;
63 std::string JSON_BROKEN(" \
70 'parentOrigin': 'CENTER', \
71 'text':'COULD NOT LOAD JSON FILE' \
77 std::string ReplaceQuotes(const std::string &single_quoted)
79 std::string s(single_quoted);
81 // wrong as no embedded quote but had regex link problems
82 std::replace(s.begin(), s.end(), '\'', '"');
87 std::string GetFileContents(const std::string &fn)
89 std::ifstream t(fn.c_str());
90 return std::string((std::istreambuf_iterator<char>(t)),
91 std::istreambuf_iterator<char>());
94 typedef std::vector<std::string> FileList;
96 void DirectoryFileList(const std::string& directory, FileList& files)
100 d = opendir(directory.c_str());
103 while ((dir = readdir(d)) != NULL)
105 if (dir->d_type == DT_REG)
107 files.push_back( directory + std::string(dir->d_name) );
115 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
117 typedef FileList Collection;
118 typedef FileList::iterator Iter;
121 DirectoryFileList(dir, allFiles);
123 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
125 size_t pos = (*iter).rfind( '.' );
126 if( pos != std::string::npos )
128 if( (*iter).substr( pos+1 ) == fileType )
130 files.push_back( (*iter) );
136 const std::string ShortName( const std::string& name )
138 size_t pos = name.rfind( '/' );
140 if( pos != std::string::npos )
143 return name.substr( pos );
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)
248 mTitleActor = DemoHelper::CreateToolBarLabel( "" );
249 // Add title to the tool bar.
250 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
253 mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
256 bool OnBackButtonPressed( Toolkit::Button button )
264 Stage stage = Stage::GetCurrent();
266 mTapDetector = TapGestureDetector::New();
267 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
271 mItemView = ItemView::New(*this);
273 mItemView.SetParentOrigin(ParentOrigin::CENTER);
274 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
275 mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
277 mLayout->SetItemSize( Vector3( stage.GetSize().width, 50, 1 ) );
279 mItemView.AddLayout( *mLayout );
281 mItemView.SetKeyboardFocusable( true );
286 if( USER_DIRECTORY.size() )
288 DirectoryFilesByType( USER_DIRECTORY, "json", files );
292 DirectoryFilesByType( DEMO_SCRIPT_DIR, "json", files );
295 std::sort(files.begin(), files.end());
298 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
300 JsonParser parser = JsonParser::New();
302 std::string data( GetFileContents( *iter ) );
304 parser.Parse( data );
306 if( parser.ParseError() )
308 std::cout << "Parser Error:" << *iter << std::endl;
309 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
313 if( parser.GetRoot() )
315 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
317 // only those with a stage section
320 mFiles.push_back( *iter );
322 mItemView.InsertItem( Item(itemId,
323 MenuItem( ShortName( *iter ) ) ),
330 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
335 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
340 // Activate the layout
341 Vector3 size(stage.GetSize());
342 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
346 void OnTap( Actor actor, const TapGesture& tap )
348 ItemId id = mItemView.GetItemId( actor );
350 LoadFromFileList( id );
353 Actor MenuItem(const std::string& text)
355 TextLabel label = TextLabel::New( ShortName( text ) );
356 label.SetStyleName( "BuilderLabel" );
357 label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
359 // Hook up tap detector
360 mTapDetector.Attach( label );
367 if( mFileWatcher.FileHasChanged() )
369 LoadFromFile( mFileWatcher.GetFilename() );
375 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
377 Stage stage = Stage::GetCurrent();
379 builder = Builder::New();
380 builder.QuitSignal().Connect( this, &ExampleApp::OnQuitOrBack );
382 Property::Map defaultDirs;
383 defaultDirs[ TOKEN_STRING(DEMO_IMAGE_DIR) ] = DEMO_IMAGE_DIR;
384 defaultDirs[ TOKEN_STRING(DEMO_MODEL_DIR) ] = DEMO_MODEL_DIR;
385 defaultDirs[ TOKEN_STRING(DEMO_SCRIPT_DIR) ] = DEMO_SCRIPT_DIR;
387 builder.AddConstants( defaultDirs );
389 // render tasks may have been setup last load so remove them
390 RenderTaskList taskList = stage.GetRenderTaskList();
391 if( taskList.GetTaskCount() > 1 )
393 typedef std::vector<RenderTask> Collection;
394 typedef Collection::iterator ColIter;
397 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
399 tasks.push_back( taskList.GetTask(i) );
402 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
404 taskList.RemoveTask(*iter);
407 RenderTask defaultTask = taskList.GetTask(0);
408 defaultTask.SetSourceActor( stage.GetRootLayer() );
409 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
412 unsigned int numChildren = layer.GetChildCount();
414 for(unsigned int i=0; i<numChildren; ++i)
416 layer.Remove( layer.GetChildAt(0) );
419 std::string data(GetFileContents(filename));
423 builder.LoadFromString(data);
427 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
430 builder.AddActors( layer );
434 void LoadFromFileList( size_t index )
436 if( index < mFiles.size())
438 const std::string& name = mFiles[index];
439 mFileWatcher.SetFilename( name );
440 LoadFromFile( name );
444 void LoadFromFile( const std::string& name )
446 ReloadJsonFile( name, mBuilder, mBuilderLayer );
448 mBuilderLayer.SetParentOrigin(ParentOrigin::BOTTOM_CENTER);
449 mBuilderLayer.SetAnchorPoint(AnchorPoint::BOTTOM_CENTER);
450 Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
451 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
452 mBuilderLayer.SetSize( size );
454 mNavigationView.Push( mBuilderLayer );
457 void Create(Application& app)
459 Stage stage = Stage::GetCurrent();
461 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
463 Layer contents = DemoHelper::CreateView( app,
470 SetTitle("Select Example");
472 mBuilderLayer = Layer::New();
474 // Create an edit mode button. (left of toolbar)
475 Toolkit::PushButton backButton = Toolkit::PushButton::New();
476 backButton.SetProperty( Toolkit::DevelButton::Property::UNSELECTED_BACKGROUND_VISUAL, EDIT_IMAGE );
477 backButton.SetProperty( Toolkit::DevelButton::Property::SELECTED_BACKGROUND_VISUAL, EDIT_IMAGE_SELECTED );
478 backButton.ClickedSignal().Connect( this, &ExampleApp::OnBackButtonPressed);
479 backButton.SetLeaveRequired( true );
480 mToolBar.AddControl( backButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
482 mNavigationView = Toolkit::NavigationView::New();
483 mNavigationView.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
484 mNavigationView.SetAnchorPoint( AnchorPoint::TOP_LEFT);
486 stage.Add( mNavigationView );
488 // Set up the background gradient.
489 Property::Array stopOffsets;
490 stopOffsets.PushBack( 0.0f );
491 stopOffsets.PushBack( 1.0f );
492 Property::Array stopColors;
493 stopColors.PushBack( Color::WHITE );
494 stopColors.PushBack( Vector4( 0.45f, 0.70f, 0.80f, 1.0f ) ); // Medium bright, pastel blue
495 const float percentageStageHeight = stage.GetSize().height * 0.6f;
497 mNavigationView.SetProperty( Toolkit::Control::Property::BACKGROUND, Dali::Property::Map()
498 .Add( Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT )
499 .Add( Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets )
500 .Add( Toolkit::GradientVisual::Property::STOP_COLOR, stopColors )
501 .Add( Toolkit::GradientVisual::Property::START_POSITION, Vector2( 0.0f, -percentageStageHeight ) )
502 .Add( Toolkit::GradientVisual::Property::END_POSITION, Vector2( 0.0f, percentageStageHeight ) )
503 .Add( Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE ) );
506 mNavigationView.Push( mItemView );
508 mTimer = Timer::New( 500 ); // ms
509 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
514 virtual unsigned int GetNumberOfItems()
516 return mFiles.size();
519 virtual Actor NewItem(unsigned int itemId)
521 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
522 return MenuItem( ShortName( mFiles[itemId] ) );
526 * Main key event handler
528 void OnKeyEvent(const KeyEvent& event)
530 if(event.state == KeyEvent::Down)
532 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
540 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
544 if ( mItemView.OnStage() )
550 mNavigationView.Pop();
557 ItemLayoutPtr mLayout;
559 Toolkit::NavigationView mNavigationView;
561 Toolkit::Control mView;
563 Toolkit::ToolBar mToolBar;
564 TextLabel mTitleActor;
568 TapGestureDetector mTapDetector;
575 FileWatcher mFileWatcher;
579 //------------------------------------------------------------------------------
583 //------------------------------------------------------------------------------
584 int DALI_EXPORT_API main(int argc, char **argv)
588 if(strcmp(argv[1], "-f") == 0)
590 USER_DIRECTORY = argv[2];
594 Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
596 ExampleApp dali_app(app);