2 * Copyright (c) 2020 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>
29 #include <dali-toolkit/devel-api/controls/navigation-view/navigation-view.h>
44 #include <dali/integration-api/debug.h>
45 #include <dali/devel-api/adaptor-framework/file-loader.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::streampos bufferSize = 0;
90 Dali::Vector<char> fileBuffer;
91 if( !Dali::FileLoader::ReadFile( fn, bufferSize, fileBuffer, FileLoader::FileType::BINARY ) )
96 return std::string( &fileBuffer[0], bufferSize );
99 typedef std::vector<std::string> FileList;
101 void DirectoryFileList(const std::string& directory, FileList& files)
105 d = opendir(directory.c_str());
108 while ((dir = readdir(d)) != NULL)
110 if (dir->d_type == DT_REG)
112 files.push_back( directory + std::string(dir->d_name) );
120 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
122 typedef FileList Collection;
123 typedef FileList::iterator Iter;
126 DirectoryFileList(dir, allFiles);
128 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
130 size_t pos = (*iter).rfind( '.' );
131 if( pos != std::string::npos )
133 if( (*iter).substr( pos+1 ) == fileType )
135 files.push_back( (*iter) );
141 const std::string ShortName( const std::string& name )
143 size_t pos = name.rfind( '/' );
145 if( pos != std::string::npos )
148 return name.substr( pos );
156 //------------------------------------------------------------------------------
160 //------------------------------------------------------------------------------
166 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
168 void SetFilename(const std::string &fn);
169 std::string GetFilename() const;
171 bool FileHasChanged(void);
172 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
176 // FileWatcher(const FileWatcher&);
177 // FileWatcher &operator=(const FileWatcher &);
179 std::time_t mLastTime;
180 std::string mstringPath;
184 FileWatcher::FileWatcher(void) : mLastTime(0)
188 bool FileWatcher::FileHasChanged(void)
192 if(0 != stat(mstringPath.c_str(), &buf))
198 if(buf.st_mtime > mLastTime)
200 mLastTime = buf.st_mtime;
205 mLastTime = buf.st_mtime;
213 FileWatcher::~FileWatcher()
217 void FileWatcher::SetFilename(const std::string &fn)
220 FileHasChanged(); // update last time
223 std::string FileWatcher::GetFilename(void) const
232 //------------------------------------------------------------------------------
236 //------------------------------------------------------------------------------
237 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
240 ExampleApp(Application &app) : mApp(app)
242 app.InitSignal().Connect(this, &ExampleApp::Create);
249 void SetTitle(const std::string& title)
253 mTitleActor = DemoHelper::CreateToolBarLabel( "" );
254 // Add title to the tool bar.
255 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
258 mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
261 bool OnBackButtonPressed( Toolkit::Button button )
269 Window window = mApp.GetWindow();
271 mTapDetector = TapGestureDetector::New();
272 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
276 mItemView = ItemView::New(*this);
278 mItemView.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER);
279 mItemView.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::CENTER);
280 mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
282 mLayout->SetItemSize( Vector3( window.GetSize().GetWidth(), 50, 1 ) );
284 mItemView.AddLayout( *mLayout );
286 mItemView.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true );
291 if( USER_DIRECTORY.size() )
293 DirectoryFilesByType( USER_DIRECTORY, "json", files );
297 DirectoryFilesByType( DEMO_SCRIPT_DIR, "json", files );
300 std::sort(files.begin(), files.end());
303 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
305 JsonParser parser = JsonParser::New();
307 std::string data( GetFileContents( *iter ) );
309 parser.Parse( data );
311 if( parser.ParseError() )
313 std::cout << "Parser Error:" << *iter << std::endl;
314 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
318 if( parser.GetRoot() )
320 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
322 // only those with a stage section
325 mFiles.push_back( *iter );
327 mItemView.InsertItem( Item(itemId,
328 MenuItem( ShortName( *iter ) ) ),
335 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
340 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
345 // Activate the layout
346 Vector3 size(window.GetSize());
347 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
351 void OnTap( Actor actor, const TapGesture& tap )
353 ItemId id = mItemView.GetItemId( actor );
355 LoadFromFileList( id );
358 Actor MenuItem(const std::string& text)
360 TextLabel label = TextLabel::New( ShortName( text ) );
361 label.SetStyleName( "BuilderLabel" );
362 label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
364 // Hook up tap detector
365 mTapDetector.Attach( label );
372 if( mFileWatcher.FileHasChanged() )
374 LoadFromFile( mFileWatcher.GetFilename() );
380 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
382 Window window = mApp.GetWindow();
384 builder = Builder::New();
385 builder.QuitSignal().Connect( this, &ExampleApp::OnQuitOrBack );
387 Property::Map defaultDirs;
388 defaultDirs[ TOKEN_STRING(DEMO_IMAGE_DIR) ] = DEMO_IMAGE_DIR;
389 defaultDirs[ TOKEN_STRING(DEMO_MODEL_DIR) ] = DEMO_MODEL_DIR;
390 defaultDirs[ TOKEN_STRING(DEMO_SCRIPT_DIR) ] = DEMO_SCRIPT_DIR;
392 builder.AddConstants( defaultDirs );
394 // render tasks may have been setup last load so remove them
395 RenderTaskList taskList = window.GetRenderTaskList();
396 if( taskList.GetTaskCount() > 1 )
398 typedef std::vector<RenderTask> Collection;
399 typedef Collection::iterator ColIter;
402 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
404 tasks.push_back( taskList.GetTask(i) );
407 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
409 taskList.RemoveTask(*iter);
412 RenderTask defaultTask = taskList.GetTask(0);
413 defaultTask.SetSourceActor( window.GetRootLayer() );
414 defaultTask.SetFrameBuffer( FrameBuffer() );
417 unsigned int numChildren = layer.GetChildCount();
419 for(unsigned int i=0; i<numChildren; ++i)
421 layer.Remove( layer.GetChildAt(0) );
424 std::string data(GetFileContents(filename));
428 builder.LoadFromString(data);
432 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
435 builder.AddActors( layer );
439 void LoadFromFileList( size_t index )
441 if( index < mFiles.size())
443 const std::string& name = mFiles[index];
444 mFileWatcher.SetFilename( name );
445 LoadFromFile( name );
449 void LoadFromFile( const std::string& name )
451 ReloadJsonFile( name, mBuilder, mBuilderLayer );
453 mBuilderLayer.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::BOTTOM_CENTER);
454 mBuilderLayer.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::BOTTOM_CENTER);
455 Dali::Vector3 size = mApp.GetWindow().GetRootLayer().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
456 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
457 mBuilderLayer.SetProperty( Actor::Property::SIZE, size );
459 mNavigationView.Push( mBuilderLayer );
462 void Create(Application& app)
464 Window window = app.GetWindow();
466 window.KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
468 Layer contents = DemoHelper::CreateView( app,
475 SetTitle("Select Example");
477 mBuilderLayer = Layer::New();
479 // Create an edit mode button. (left of toolbar)
480 Toolkit::PushButton backButton = Toolkit::PushButton::New();
481 backButton.SetProperty( Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, EDIT_IMAGE );
482 backButton.SetProperty( Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, EDIT_IMAGE_SELECTED );
483 backButton.ClickedSignal().Connect( this, &ExampleApp::OnBackButtonPressed);
484 backButton.SetProperty( Actor::Property::LEAVE_REQUIRED, true );
485 mToolBar.AddControl( backButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
487 mNavigationView = Toolkit::NavigationView::New();
488 mNavigationView.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
489 mNavigationView.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
491 window.Add( mNavigationView );
493 // Set up the background gradient.
494 Property::Array stopOffsets;
495 stopOffsets.PushBack( 0.0f );
496 stopOffsets.PushBack( 1.0f );
497 Property::Array stopColors;
498 stopColors.PushBack( Color::WHITE );
499 stopColors.PushBack( Vector4( 0.45f, 0.70f, 0.80f, 1.0f ) ); // Medium bright, pastel blue
500 const float percentageWindowHeight = window.GetSize().GetHeight() * 0.6f;
502 mNavigationView.SetProperty( Toolkit::Control::Property::BACKGROUND, Dali::Property::Map()
503 .Add( Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT )
504 .Add( Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets )
505 .Add( Toolkit::GradientVisual::Property::STOP_COLOR, stopColors )
506 .Add( Toolkit::GradientVisual::Property::START_POSITION, Vector2( 0.0f, -percentageWindowHeight ) )
507 .Add( Toolkit::GradientVisual::Property::END_POSITION, Vector2( 0.0f, percentageWindowHeight ) )
508 .Add( Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE ) );
511 mNavigationView.Push( mItemView );
513 mTimer = Timer::New( 500 ); // ms
514 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
519 virtual unsigned int GetNumberOfItems()
521 return mFiles.size();
524 virtual Actor NewItem(unsigned int itemId)
526 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
527 return MenuItem( ShortName( mFiles[itemId] ) );
531 * Main key event handler
533 void OnKeyEvent(const KeyEvent& event)
535 if(event.state == KeyEvent::Down)
537 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
545 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
549 if ( mItemView.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
555 mNavigationView.Pop();
562 ItemLayoutPtr mLayout;
564 Toolkit::NavigationView mNavigationView;
566 Toolkit::Control mView;
568 Toolkit::ToolBar mToolBar;
569 TextLabel mTitleActor;
573 TapGestureDetector mTapDetector;
580 FileWatcher mFileWatcher;
584 //------------------------------------------------------------------------------
588 //------------------------------------------------------------------------------
589 int DALI_EXPORT_API main(int argc, char **argv)
593 if(strcmp(argv[1], "-f") == 0)
595 USER_DIRECTORY = argv[2];
599 Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
601 ExampleApp dali_app(app);