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 <dali/devel-api/adaptor-framework/file-loader.h>
47 #include "shared/view.h"
49 #define TOKEN_STRING(x) #x
52 using namespace Dali::Toolkit;
57 const char* BACKGROUND_IMAGE( "" );
58 const char* TOOLBAR_IMAGE( DEMO_IMAGE_DIR "top-bar.png" );
59 const char* EDIT_IMAGE( DEMO_IMAGE_DIR "icon-change.png" );
60 const char* EDIT_IMAGE_SELECTED( DEMO_IMAGE_DIR "icon-change-selected.png" );
62 std::string USER_DIRECTORY;
64 std::string JSON_BROKEN(" \
71 'parentOrigin': 'CENTER', \
72 'text':'COULD NOT LOAD JSON FILE' \
78 std::string ReplaceQuotes(const std::string &single_quoted)
80 std::string s(single_quoted);
82 // wrong as no embedded quote but had regex link problems
83 std::replace(s.begin(), s.end(), '\'', '"');
88 std::string GetFileContents(const std::string &fn)
90 std::streampos bufferSize = 0;
91 Dali::Vector<char> fileBuffer;
92 if( !Dali::FileLoader::ReadFile( fn, bufferSize, fileBuffer, FileLoader::FileType::BINARY ) )
97 return std::string( &fileBuffer[0], bufferSize );
100 typedef std::vector<std::string> FileList;
102 void DirectoryFileList(const std::string& directory, FileList& files)
106 d = opendir(directory.c_str());
109 while ((dir = readdir(d)) != NULL)
111 if (dir->d_type == DT_REG)
113 files.push_back( directory + std::string(dir->d_name) );
121 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
123 typedef FileList Collection;
124 typedef FileList::iterator Iter;
127 DirectoryFileList(dir, allFiles);
129 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
131 size_t pos = (*iter).rfind( '.' );
132 if( pos != std::string::npos )
134 if( (*iter).substr( pos+1 ) == fileType )
136 files.push_back( (*iter) );
142 const std::string ShortName( const std::string& name )
144 size_t pos = name.rfind( '/' );
146 if( pos != std::string::npos )
149 return name.substr( pos );
157 //------------------------------------------------------------------------------
161 //------------------------------------------------------------------------------
167 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
169 void SetFilename(const std::string &fn);
170 std::string GetFilename() const;
172 bool FileHasChanged(void);
173 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
177 // FileWatcher(const FileWatcher&);
178 // FileWatcher &operator=(const FileWatcher &);
180 std::time_t mLastTime;
181 std::string mstringPath;
185 FileWatcher::FileWatcher(void) : mLastTime(0)
189 bool FileWatcher::FileHasChanged(void)
193 if(0 != stat(mstringPath.c_str(), &buf))
199 if(buf.st_mtime > mLastTime)
201 mLastTime = buf.st_mtime;
206 mLastTime = buf.st_mtime;
214 FileWatcher::~FileWatcher()
218 void FileWatcher::SetFilename(const std::string &fn)
221 FileHasChanged(); // update last time
224 std::string FileWatcher::GetFilename(void) const
233 //------------------------------------------------------------------------------
237 //------------------------------------------------------------------------------
238 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
241 ExampleApp(Application &app) : mApp(app)
243 app.InitSignal().Connect(this, &ExampleApp::Create);
250 void SetTitle(const std::string& title)
254 mTitleActor = DemoHelper::CreateToolBarLabel( "" );
255 // Add title to the tool bar.
256 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
259 mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
262 bool OnBackButtonPressed( Toolkit::Button button )
270 Stage stage = Stage::GetCurrent();
272 mTapDetector = TapGestureDetector::New();
273 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
277 mItemView = ItemView::New(*this);
279 mItemView.SetParentOrigin(ParentOrigin::CENTER);
280 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
281 mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
283 mLayout->SetItemSize( Vector3( stage.GetSize().width, 50, 1 ) );
285 mItemView.AddLayout( *mLayout );
287 mItemView.SetKeyboardFocusable( true );
292 if( USER_DIRECTORY.size() )
294 DirectoryFilesByType( USER_DIRECTORY, "json", files );
298 DirectoryFilesByType( DEMO_SCRIPT_DIR, "json", files );
301 std::sort(files.begin(), files.end());
304 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
306 JsonParser parser = JsonParser::New();
308 std::string data( GetFileContents( *iter ) );
310 parser.Parse( data );
312 if( parser.ParseError() )
314 std::cout << "Parser Error:" << *iter << std::endl;
315 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
319 if( parser.GetRoot() )
321 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
323 // only those with a stage section
326 mFiles.push_back( *iter );
328 mItemView.InsertItem( Item(itemId,
329 MenuItem( ShortName( *iter ) ) ),
336 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
341 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
346 // Activate the layout
347 Vector3 size(stage.GetSize());
348 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
352 void OnTap( Actor actor, const TapGesture& tap )
354 ItemId id = mItemView.GetItemId( actor );
356 LoadFromFileList( id );
359 Actor MenuItem(const std::string& text)
361 TextLabel label = TextLabel::New( ShortName( text ) );
362 label.SetStyleName( "BuilderLabel" );
363 label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
365 // Hook up tap detector
366 mTapDetector.Attach( label );
373 if( mFileWatcher.FileHasChanged() )
375 LoadFromFile( mFileWatcher.GetFilename() );
381 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
383 Stage stage = Stage::GetCurrent();
385 builder = Builder::New();
386 builder.QuitSignal().Connect( this, &ExampleApp::OnQuitOrBack );
388 Property::Map defaultDirs;
389 defaultDirs[ TOKEN_STRING(DEMO_IMAGE_DIR) ] = DEMO_IMAGE_DIR;
390 defaultDirs[ TOKEN_STRING(DEMO_MODEL_DIR) ] = DEMO_MODEL_DIR;
391 defaultDirs[ TOKEN_STRING(DEMO_SCRIPT_DIR) ] = DEMO_SCRIPT_DIR;
393 builder.AddConstants( defaultDirs );
395 // render tasks may have been setup last load so remove them
396 RenderTaskList taskList = stage.GetRenderTaskList();
397 if( taskList.GetTaskCount() > 1 )
399 typedef std::vector<RenderTask> Collection;
400 typedef Collection::iterator ColIter;
403 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
405 tasks.push_back( taskList.GetTask(i) );
408 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
410 taskList.RemoveTask(*iter);
413 RenderTask defaultTask = taskList.GetTask(0);
414 defaultTask.SetSourceActor( stage.GetRootLayer() );
415 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
418 unsigned int numChildren = layer.GetChildCount();
420 for(unsigned int i=0; i<numChildren; ++i)
422 layer.Remove( layer.GetChildAt(0) );
425 std::string data(GetFileContents(filename));
429 builder.LoadFromString(data);
433 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
436 builder.AddActors( layer );
440 void LoadFromFileList( size_t index )
442 if( index < mFiles.size())
444 const std::string& name = mFiles[index];
445 mFileWatcher.SetFilename( name );
446 LoadFromFile( name );
450 void LoadFromFile( const std::string& name )
452 ReloadJsonFile( name, mBuilder, mBuilderLayer );
454 mBuilderLayer.SetParentOrigin(ParentOrigin::BOTTOM_CENTER);
455 mBuilderLayer.SetAnchorPoint(AnchorPoint::BOTTOM_CENTER);
456 Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
457 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
458 mBuilderLayer.SetSize( size );
460 mNavigationView.Push( mBuilderLayer );
463 void Create(Application& app)
465 Stage stage = Stage::GetCurrent();
467 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
469 Layer contents = DemoHelper::CreateView( app,
476 SetTitle("Select Example");
478 mBuilderLayer = Layer::New();
480 // Create an edit mode button. (left of toolbar)
481 Toolkit::PushButton backButton = Toolkit::PushButton::New();
482 backButton.SetProperty( Toolkit::DevelButton::Property::UNSELECTED_BACKGROUND_VISUAL, EDIT_IMAGE );
483 backButton.SetProperty( Toolkit::DevelButton::Property::SELECTED_BACKGROUND_VISUAL, EDIT_IMAGE_SELECTED );
484 backButton.ClickedSignal().Connect( this, &ExampleApp::OnBackButtonPressed);
485 backButton.SetLeaveRequired( true );
486 mToolBar.AddControl( backButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
488 mNavigationView = Toolkit::NavigationView::New();
489 mNavigationView.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
490 mNavigationView.SetAnchorPoint( AnchorPoint::TOP_LEFT);
492 stage.Add( mNavigationView );
494 // Set up the background gradient.
495 Property::Array stopOffsets;
496 stopOffsets.PushBack( 0.0f );
497 stopOffsets.PushBack( 1.0f );
498 Property::Array stopColors;
499 stopColors.PushBack( Color::WHITE );
500 stopColors.PushBack( Vector4( 0.45f, 0.70f, 0.80f, 1.0f ) ); // Medium bright, pastel blue
501 const float percentageStageHeight = stage.GetSize().height * 0.6f;
503 mNavigationView.SetProperty( Toolkit::Control::Property::BACKGROUND, Dali::Property::Map()
504 .Add( Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT )
505 .Add( Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets )
506 .Add( Toolkit::GradientVisual::Property::STOP_COLOR, stopColors )
507 .Add( Toolkit::GradientVisual::Property::START_POSITION, Vector2( 0.0f, -percentageStageHeight ) )
508 .Add( Toolkit::GradientVisual::Property::END_POSITION, Vector2( 0.0f, percentageStageHeight ) )
509 .Add( Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE ) );
512 mNavigationView.Push( mItemView );
514 mTimer = Timer::New( 500 ); // ms
515 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
520 virtual unsigned int GetNumberOfItems()
522 return mFiles.size();
525 virtual Actor NewItem(unsigned int itemId)
527 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
528 return MenuItem( ShortName( mFiles[itemId] ) );
532 * Main key event handler
534 void OnKeyEvent(const KeyEvent& event)
536 if(event.state == KeyEvent::Down)
538 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
546 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
550 if ( mItemView.OnStage() )
556 mNavigationView.Pop();
563 ItemLayoutPtr mLayout;
565 Toolkit::NavigationView mNavigationView;
567 Toolkit::Control mView;
569 Toolkit::ToolBar mToolBar;
570 TextLabel mTitleActor;
574 TapGestureDetector mTapDetector;
581 FileWatcher mFileWatcher;
585 //------------------------------------------------------------------------------
589 //------------------------------------------------------------------------------
590 int DALI_EXPORT_API main(int argc, char **argv)
594 if(strcmp(argv[1], "-f") == 0)
596 USER_DIRECTORY = argv[2];
600 Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
602 ExampleApp dali_app(app);