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" );
57 std::string USER_DIRECTORY;
59 std::string JSON_BROKEN(" \
66 'parent-origin': 'CENTER', \
67 'text':'COULD NOT LOAD JSON FILE' \
73 std::string ReplaceQuotes(const std::string &single_quoted)
75 std::string s(single_quoted);
77 // wrong as no embedded quote but had regex link problems
78 std::replace(s.begin(), s.end(), '\'', '"');
83 std::string GetFileContents(const std::string &fn)
85 std::ifstream t(fn.c_str());
86 return std::string((std::istreambuf_iterator<char>(t)),
87 std::istreambuf_iterator<char>());
90 typedef std::vector<std::string> FileList;
92 void DirectoryFileList(const std::string& directory, FileList& files)
96 d = opendir(directory.c_str());
99 while ((dir = readdir(d)) != NULL)
101 if (dir->d_type == DT_REG)
103 files.push_back( directory + std::string(dir->d_name) );
111 void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
113 typedef FileList Collection;
114 typedef FileList::iterator Iter;
117 DirectoryFileList(dir, allFiles);
119 for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
121 size_t pos = (*iter).rfind( '.' );
122 if( pos != std::string::npos )
124 if( (*iter).substr( pos+1 ) == fileType )
126 files.push_back( (*iter) );
132 const std::string ShortName( const std::string& name )
134 size_t pos = name.rfind( '/' );
136 if( pos != std::string::npos )
138 return name.substr( pos );
146 //------------------------------------------------------------------------------
150 //------------------------------------------------------------------------------
156 explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
158 void SetFilename(const std::string &fn);
159 std::string GetFilename() const;
161 bool FileHasChanged(void);
162 std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
166 // FileWatcher(const FileWatcher&);
167 // FileWatcher &operator=(const FileWatcher &);
169 std::time_t mLastTime;
170 std::string mstringPath;
174 FileWatcher::FileWatcher(void) : mLastTime(0)
178 bool FileWatcher::FileHasChanged(void)
182 if(0 != stat(mstringPath.c_str(), &buf))
188 if(buf.st_mtime > mLastTime)
190 mLastTime = buf.st_mtime;
195 mLastTime = buf.st_mtime;
203 FileWatcher::~FileWatcher()
207 void FileWatcher::SetFilename(const std::string &fn)
210 FileHasChanged(); // update last time
213 std::string FileWatcher::GetFilename(void) const
222 //------------------------------------------------------------------------------
226 //------------------------------------------------------------------------------
227 class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
230 ExampleApp(Application &app) : mApp(app)
232 app.InitSignal().Connect(this, &ExampleApp::Create);
239 void SetTitle(const std::string& title)
243 mTitleActor = DemoHelper::CreateToolBarLabel( "" );
244 // Add title to the tool bar.
245 mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
248 mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
251 bool OnToolSelectLayout( Toolkit::Button button )
253 bool on = mItemView.IsVisible();
267 void LeaveSelection()
272 void EnterSelection()
274 Stage stage = Stage::GetCurrent();
275 stage.SetBackgroundColor( Color::WHITE );
277 mTapDetector = TapGestureDetector::New();
278 mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
282 stage.Remove( mItemView );
287 mItemView = ItemView::New(*this);
288 stage.Add( mItemView );
289 mItemView.SetParentOrigin(ParentOrigin::CENTER);
290 mItemView.SetAnchorPoint(AnchorPoint::CENTER);
291 mLayout = DefaultItemLayout::New( DefaultItemLayout::LIST );
293 mLayout->SetItemSize( Vector3( stage.GetSize().width, 50, 1 ) );
295 mItemView.AddLayout( *mLayout );
297 mItemView.SetKeyboardFocusable( true );
302 if( USER_DIRECTORY.size() )
304 DirectoryFilesByType( USER_DIRECTORY, "json", files );
308 DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
311 std::sort(files.begin(), files.end());
314 for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
316 JsonParser parser = JsonParser::New();
318 std::string data( GetFileContents( *iter ) );
320 parser.Parse( data );
322 if( parser.ParseError() )
324 std::cout << "Parser Error:" << *iter << std::endl;
325 std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
329 if( parser.GetRoot() )
331 if( const TreeNode* node = parser.GetRoot()->Find("stage") )
333 // only those with a stage section
336 mFiles.push_back( *iter );
338 mItemView.InsertItem( Item(itemId,
339 MenuItem( ShortName( *iter ) ) ),
346 std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
351 std::cout << "Ignored file (no stage section):" << *iter << std::endl;
356 // Display item view on the stage
357 stage.Add( mItemView );
359 mItemView.SetVisible( true );
360 mBuilderLayer.SetVisible( false );
364 // Activate the layout
365 Vector3 size(stage.GetSize());
366 mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
371 mTapDetector.Reset();
373 mItemView.SetVisible( false );
374 mBuilderLayer.SetVisible( true );
379 void OnTap( Actor actor, const TapGesture& tap )
381 ItemId id = mItemView.GetItemId( actor );
383 LoadFromFileList( id );
386 Actor MenuItem(const std::string& text)
388 TextLabel label = TextLabel::New( ShortName( text ) );
389 label.SetProperty( Dali::Toolkit::Control::Property::STYLE_NAME, "builderlabel" );
390 label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
392 // Hook up tap detector
393 mTapDetector.Attach( label );
400 if( mFileWatcher.FileHasChanged() )
402 LoadFromFile( mFileWatcher.GetFilename() );
408 void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
410 Stage stage = Stage::GetCurrent();
412 builder = Builder::New();
413 builder.QuitSignal().Connect( this, &ExampleApp::OnBuilderQuit );
415 Property::Map defaultDirs;
416 defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
417 defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;
418 defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
420 builder.AddConstants( defaultDirs );
422 // render tasks may have been setup last load so remove them
423 RenderTaskList taskList = stage.GetRenderTaskList();
424 if( taskList.GetTaskCount() > 1 )
426 typedef std::vector<RenderTask> Collection;
427 typedef Collection::iterator ColIter;
430 for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
432 tasks.push_back( taskList.GetTask(i) );
435 for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
437 taskList.RemoveTask(*iter);
440 RenderTask defaultTask = taskList.GetTask(0);
441 defaultTask.SetSourceActor( stage.GetRootLayer() );
442 defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
445 unsigned int numChildren = layer.GetChildCount();
447 for(unsigned int i=0; i<numChildren; ++i)
449 layer.Remove( layer.GetChildAt(0) );
452 std::string data(GetFileContents(filename));
456 builder.LoadFromString(data);
460 builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
463 builder.AddActors( layer );
467 void LoadFromFileList( size_t index )
469 if( index < mFiles.size())
471 const std::string& name = mFiles[index];
472 mFileWatcher.SetFilename( name );
473 LoadFromFile( name );
477 void LoadFromFile( const std::string& name )
479 ReloadJsonFile( name, mBuilder, mBuilderLayer );
481 // do this here as GetCurrentSize()
482 mBuilderLayer.SetParentOrigin(ParentOrigin::CENTER);
483 mBuilderLayer.SetAnchorPoint(AnchorPoint::CENTER);
484 Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
485 size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
486 mBuilderLayer.SetSize( size );
488 mBuilderLayer.LowerToBottom();
489 Stage::GetCurrent().GetRootLayer().RaiseToTop();
494 void Create(Application& app)
496 Stage stage = Stage::GetCurrent();
498 Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
500 Layer contents = DemoHelper::CreateView( app,
509 mBuilderLayer = Layer::New();
510 stage.GetRootLayer().Add(mBuilderLayer);
513 // Create an edit mode button. (left of toolbar)
514 Toolkit::PushButton editButton = Toolkit::PushButton::New();
515 editButton.SetBackgroundImage( ResourceImage::New( EDIT_IMAGE ) );
516 editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
517 editButton.SetLeaveRequired( true );
518 mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
522 mTimer = Timer::New( 500 ); // ms
523 mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
528 virtual unsigned int GetNumberOfItems()
530 return mFiles.size();
533 virtual Actor NewItem(unsigned int itemId)
535 DALI_ASSERT_DEBUG( itemId < mFiles.size() );
536 return MenuItem( ShortName( mFiles[itemId] ) );
540 * Main key event handler
542 void OnKeyEvent(const KeyEvent& event)
544 if(event.state == KeyEvent::Down)
546 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
548 if ( mItemView.IsVisible() )
561 * Event handler when Builder wants to quit (we only want to close the shown json unless we're at the top-level)
565 if ( mItemView.IsVisible() )
578 ItemLayoutPtr mLayout;
581 Toolkit::Control mView;
582 unsigned int mOrientation;
584 Toolkit::ToolBar mToolBar;
585 TextLabel mTitleActor; ///< The Toolbar's Title.
589 Toolkit::Popup mMenu;
591 TapGestureDetector mTapDetector;
598 FileWatcher mFileWatcher;
604 //------------------------------------------------------------------------------
608 //------------------------------------------------------------------------------
609 int main(int argc, char **argv)
613 if(strcmp(argv[1], "-f") == 0)
615 USER_DIRECTORY = argv[2];
619 Application app = Application::New(&argc, &argv, DALI_DEMO_THEME_PATH);
621 ExampleApp dali_app(app);