2 * Copyright (c) 2016 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 "shared/view.h"
47 #define TOKEN_STRING(x) #x
50 using namespace Dali::Toolkit;
55 const char* BACKGROUND_IMAGE( "" );
56 const char* TOOLBAR_IMAGE( DEMO_IMAGE_DIR "top-bar.png" );
57 const char* EDIT_IMAGE( DEMO_IMAGE_DIR "icon-change.png" );
58 const char* EDIT_IMAGE_SELECTED( DEMO_IMAGE_DIR "icon-change-selected.png" );
60 std::string USER_DIRECTORY;
62 std::string JSON_BROKEN(" \
69 'parentOrigin': 'CENTER', \
70 'text':'COULD NOT LOAD JSON FILE' \
76 std::string ReplaceQuotes(const std::string &single_quoted)
78 std::string s(single_quoted);
80 // wrong as no embedded quote but had regex link problems
81 std::replace(s.begin(), s.end(), '\'', '"');
86 std::string GetFileContents(const std::string &fn)
88 std::ifstream t(fn.c_str());
89 return std::string((std::istreambuf_iterator<char>(t)),
90 std::istreambuf_iterator<char>());
93 typedef std::vector<std::string> FileList;
95 void DirectoryFileList(const std::string& directory, FileList& files)
99 d = opendir(directory.c_str());
102 while ((dir = readdir(d)) != NULL)
104 if (dir->d_type == DT_REG)
106 files.push_back( directory + std::string(dir->d_name) );
114 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
116 typedef FileList Collection;
117 typedef FileList::iterator Iter;
120 DirectoryFileList(dir, allFiles);
122 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
124 size_t pos = (*iter).rfind( '.' );
125 if( pos != std::string::npos )
127 if( (*iter).substr( pos+1 ) == fileType )
129 files.push_back( (*iter) );
135 const std::string ShortName( const std::string& name )
137 size_t pos = name.rfind( '/' );
139 if( pos != std::string::npos )
142 return name.substr( pos );
150 //------------------------------------------------------------------------------
154 //------------------------------------------------------------------------------
160 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
162 void SetFilename(const std::string &fn);
163 std::string GetFilename() const;
165 bool FileHasChanged(void);
166 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
170 // FileWatcher(const FileWatcher&);
171 // FileWatcher &operator=(const FileWatcher &);
173 std::time_t mLastTime;
174 std::string mstringPath;
178 FileWatcher::FileWatcher(void) : mLastTime(0)
182 bool FileWatcher::FileHasChanged(void)
186 if(0 != stat(mstringPath.c_str(), &buf))
192 if(buf.st_mtime > mLastTime)
194 mLastTime = buf.st_mtime;
199 mLastTime = buf.st_mtime;
207 FileWatcher::~FileWatcher()
211 void FileWatcher::SetFilename(const std::string &fn)
214 FileHasChanged(); // update last time
217 std::string FileWatcher::GetFilename(void) const
226 //------------------------------------------------------------------------------
230 //------------------------------------------------------------------------------
231 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
234 ExampleApp(Application &app) : mApp(app)
236 app.InitSignal().Connect(this, &ExampleApp::Create);
243 void SetTitle(const std::string& title)
247 mTitleActor = DemoHelper::CreateToolBarLabel( "" );
248 // Add title to the tool bar.
249 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
252 mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
255 bool OnBackButtonPressed( Toolkit::Button button )
263 Stage stage = Stage::GetCurrent();
265 mTapDetector = TapGestureDetector::New();
266 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
270 mItemView = ItemView::New(*this);
272 mItemView.SetParentOrigin(ParentOrigin::CENTER);
273 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
274 mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
276 mLayout->SetItemSize( Vector3( stage.GetSize().width, 50, 1 ) );
278 mItemView.AddLayout( *mLayout );
280 mItemView.SetKeyboardFocusable( true );
285 if( USER_DIRECTORY.size() )
287 DirectoryFilesByType( USER_DIRECTORY, "json", files );
291 DirectoryFilesByType( DEMO_SCRIPT_DIR, "json", files );
294 std::sort(files.begin(), files.end());
297 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
299 JsonParser parser = JsonParser::New();
301 std::string data( GetFileContents( *iter ) );
303 parser.Parse( data );
305 if( parser.ParseError() )
307 std::cout << "Parser Error:" << *iter << std::endl;
308 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
312 if( parser.GetRoot() )
314 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
316 // only those with a stage section
319 mFiles.push_back( *iter );
321 mItemView.InsertItem( Item(itemId,
322 MenuItem( ShortName( *iter ) ) ),
329 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
334 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
339 // Activate the layout
340 Vector3 size(stage.GetSize());
341 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
345 void OnTap( Actor actor, const TapGesture& tap )
347 ItemId id = mItemView.GetItemId( actor );
349 LoadFromFileList( id );
352 Actor MenuItem(const std::string& text)
354 TextLabel label = TextLabel::New( ShortName( text ) );
355 label.SetStyleName( "BuilderLabel" );
356 label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
358 // Hook up tap detector
359 mTapDetector.Attach( label );
366 if( mFileWatcher.FileHasChanged() )
368 LoadFromFile( mFileWatcher.GetFilename() );
374 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
376 Stage stage = Stage::GetCurrent();
378 builder = Builder::New();
379 builder.QuitSignal().Connect( this, &ExampleApp::OnQuitOrBack );
381 Property::Map defaultDirs;
382 defaultDirs[ TOKEN_STRING(DEMO_IMAGE_DIR) ] = DEMO_IMAGE_DIR;
383 defaultDirs[ TOKEN_STRING(DEMO_MODEL_DIR) ] = DEMO_MODEL_DIR;
384 defaultDirs[ TOKEN_STRING(DEMO_SCRIPT_DIR) ] = DEMO_SCRIPT_DIR;
386 builder.AddConstants( defaultDirs );
388 // render tasks may have been setup last load so remove them
389 RenderTaskList taskList = stage.GetRenderTaskList();
390 if( taskList.GetTaskCount() > 1 )
392 typedef std::vector<RenderTask> Collection;
393 typedef Collection::iterator ColIter;
396 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
398 tasks.push_back( taskList.GetTask(i) );
401 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
403 taskList.RemoveTask(*iter);
406 RenderTask defaultTask = taskList.GetTask(0);
407 defaultTask.SetSourceActor( stage.GetRootLayer() );
408 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
411 unsigned int numChildren = layer.GetChildCount();
413 for(unsigned int i=0; i<numChildren; ++i)
415 layer.Remove( layer.GetChildAt(0) );
418 std::string data(GetFileContents(filename));
422 builder.LoadFromString(data);
426 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
429 builder.AddActors( layer );
433 void LoadFromFileList( size_t index )
435 if( index < mFiles.size())
437 const std::string& name = mFiles[index];
438 mFileWatcher.SetFilename( name );
439 LoadFromFile( name );
443 void LoadFromFile( const std::string& name )
445 ReloadJsonFile( name, mBuilder, mBuilderLayer );
447 mBuilderLayer.SetParentOrigin(ParentOrigin::BOTTOM_CENTER);
448 mBuilderLayer.SetAnchorPoint(AnchorPoint::BOTTOM_CENTER);
449 Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
450 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
451 mBuilderLayer.SetSize( size );
453 mNavigationView.Push( mBuilderLayer );
456 void Create(Application& app)
458 Stage stage = Stage::GetCurrent();
460 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
462 Layer contents = DemoHelper::CreateView( app,
469 SetTitle("Select Example");
471 mBuilderLayer = Layer::New();
473 // Create an edit mode button. (left of toolbar)
474 Toolkit::PushButton backButton = Toolkit::PushButton::New();
475 backButton.SetUnselectedImage( EDIT_IMAGE );
476 backButton.SetSelectedImage( EDIT_IMAGE_SELECTED );
477 backButton.ClickedSignal().Connect( this, &ExampleApp::OnBackButtonPressed);
478 backButton.SetLeaveRequired( true );
479 mToolBar.AddControl( backButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
481 mNavigationView = Toolkit::NavigationView::New();
482 mNavigationView.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
483 mNavigationView.SetAnchorPoint( AnchorPoint::TOP_LEFT);
485 stage.Add( mNavigationView );
487 // Set up the background gradient.
488 Property::Array stopOffsets;
489 stopOffsets.PushBack( 0.0f );
490 stopOffsets.PushBack( 1.0f );
491 Property::Array stopColors;
492 stopColors.PushBack( Color::WHITE );
493 stopColors.PushBack( Vector4( 0.45f, 0.70f, 0.80f, 1.0f ) ); // Medium bright, pastel blue
494 const float percentageStageHeight = stage.GetSize().height * 0.6f;
496 mNavigationView.SetProperty( Toolkit::Control::Property::BACKGROUND, Dali::Property::Map()
497 .Add( Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT )
498 .Add( Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets )
499 .Add( Toolkit::GradientVisual::Property::STOP_COLOR, stopColors )
500 .Add( Toolkit::GradientVisual::Property::START_POSITION, Vector2( 0.0f, -percentageStageHeight ) )
501 .Add( Toolkit::GradientVisual::Property::END_POSITION, Vector2( 0.0f, percentageStageHeight ) )
502 .Add( Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE ) );
505 mNavigationView.Push( mItemView );
507 mTimer = Timer::New( 500 ); // ms
508 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
513 virtual unsigned int GetNumberOfItems()
515 return mFiles.size();
518 virtual Actor NewItem(unsigned int itemId)
520 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
521 return MenuItem( ShortName( mFiles[itemId] ) );
525 * Main key event handler
527 void OnKeyEvent(const KeyEvent& event)
529 if(event.state == KeyEvent::Down)
531 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
539 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
543 if ( mItemView.OnStage() )
549 mNavigationView.Pop();
556 ItemLayoutPtr mLayout;
558 Toolkit::NavigationView mNavigationView;
560 Toolkit::Control mView;
562 Toolkit::ToolBar mToolBar;
563 TextLabel mTitleActor;
567 TapGestureDetector mTapDetector;
574 FileWatcher mFileWatcher;
578 //------------------------------------------------------------------------------
582 //------------------------------------------------------------------------------
583 int DALI_EXPORT_API main(int argc, char **argv)
587 if(strcmp(argv[1], "-f") == 0)
589 USER_DIRECTORY = argv[2];
593 Application app = Application::New(&argc, &argv, DEMO_THEME_PATH);
595 ExampleApp dali_app(app);